異步任務的理解

異步任務的理解

    邏輯上:以多線程的方式完成的功能需求
java

    API上:指AsyncTask類
android

  AsyncTask的理解:
多線程

    在沒有AsyncTask以前,咱們用Handler+Thread就能夠實現異步任務的功能需求
app

    AsyncTask是對Handler和Thread的封裝,使用它編碼更簡潔,更高效
異步

相關API


下載遠程APK並安裝實例

public class MessageActivity extends Activity implements OnClickListener{

	private File apkFile;
	private ProgressDialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message);
	
	}

	/**
	 * 下載APK
	 * @param v
	 */
public void getSubmit3(View v){
	//啓動異步任務處理
	new AsyncTask<Void, Integer, Void>() {
		//1.主線程,顯示提示視圖
		protected void onPreExecute() {
			dialog = new ProgressDialog(MessageActivity.this);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.show();
			//主播用於保存APK文件的File對象:/storage/sdcard/Android/package_name/files/xxx.apk
			apkFile = new File(getExternalFilesDir(null),"update.apk");
		};
		//2.分線程,聯網請求
		@Override
		protected Void doInBackground(Void... params) {
			try {
				String path = "http://localhost:8089/xxxxx/xxx.apk";
				URL url;
				url = new URL(path);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				//2.設置
				connection.setConnectTimeout(5000);
				//connection.setRequestMethod("GET");
				connection.setReadTimeout(50000);
				//3.連接
				connection.connect();
				//4.請求並獲得響應碼200
				int  responseCode = connection.getResponseCode();
				if(responseCode==200){
					//設置dialog的最大精度
					dialog.setMax(connection.getContentLength());
					//5.獲得包含APK文件數據的InputStream
					InputStream is =connection.getInputStream();
					//6.建立apkFile的FileOutputStream
					FileOutputStream fos = new FileOutputStream(apkFile);
					//7.邊寫邊讀
					byte[] buffer = new byte[1024];
					int len =-1;
					while((len=is.read(buffer))!=-1){
						fos.write(buffer,0,len);
						//8.顯示下載進度
						//dialog.incrementProgressBy(len);
						//休息一會(模擬網速慢)
						SystemClock.sleep(50);
						//在分線程中,發佈當前進度
						publishProgress(len);
					}
					fos.close();
					is.close();
					
				}
				//9.下載完成,關閉
				connection.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		return null;
	}
	
		
		//3.主線程,更新界面
		
		protected void onPostExecute(Void result) {
			dialog.dismiss();
			installAPK();
		};
		//主線程中更新進度(在publishProgress()以後執行)
		protected  void onProgressUpdate(Integer[] values) {
			dialog.incrementProgressBy(values[0]);
		};
		
	}.execute();
}
/**
 * 啓動安裝APK
 */
private void installAPK() {
	Intent intent=new Intent("android.intent.action.INSTALL_PACKAGE");
	intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
	startActivity(intent);
	
}

異步任務過程圖解

相關文章
相關標籤/搜索