异步任务的理解
逻辑上:以多线程的方式完成的功能需求
API上:指AsyncTask类
AsyncTask的理解:
在没有AsyncTask之前,我们用Handler+Thread就可以实现异步任务的功能需求
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() { //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); }