异步任务的理解

异步任务的理解

    逻辑上:以多线程的方式完成的功能需求
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);
	
}

异步任务过程图解

相关文章
相关标签/搜索