介绍
AsyncTask使UI线程更适用。这个类允许你在UI线程上执行后台操作并发布结果,而不必操作线程或处理程序。AsyncTask是一个围绕Thread和Handler来设计的辅助类,不构成一个通用的线程框架。AsyncTask应该被用于短作业(最多几秒钟)。如果你需要保持线程运行很长一段时间,强烈建议你使用java.util.concurrent包提供的API,比如 Executor, ThreadPoolExecutor和FutureTask。
异步任务定义为在后台线程上运行的计算,再将其结果发布在UI线程上。一个异步任务由3个泛型 (Params、 Progress 、Result),4个步骤(onPreExecute、doInBackground、onProgressUpdate 、onPostExecute)定义。
使用
AsyncTask需要通过实现子类来使用。
创建AsyncTask
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress)
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
执行AsyncTask
new DownloadFilesTask().execute(url1, url2, url3);
AsyncTask的泛型
1.Params
2.Progress 后台的执行进度
3.Result 后台执行的结果
并非所有类型都总是由异步任务使用。如:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
4个步骤
1.onPreExecute() 任务执行前在UI线程中执行。此步骤通常用于设置任务,例如在用户界面中显示进度条。
2.doInBackground(Params…) onPreExecute()执行结束后,在后台进程中调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数被传递给这个步骤。计算结果必须由这个步骤返回,并返回到最后一步。这一步也可以使用publishprogress(Progress…)发布一个或多个单位的进展。在 onProgressUpdate(Progress…)中将这些值发布到UI线程上。
3.onProgressUpdate(Progress…) 调用publishprogress(Progress…)后在UI线程中调用。此方法用于在UI界面显示后台的计算数据。比如,可以使用文本和进度条来显示后台执行的情况。
4.onPostExecute(Result) 当后台执行结束时在UI线程中调用。
任务取消
任务在任何时候调用onCancel(boolean)都可取消。
应用强制更新示例:
创建AsyncTask:
class DownloadTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... strings) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
outputStream = context.openFileOutput("xxx.apk",
MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
URL url = new URL(strings[0]);
URLConnection conn = url.openConnection();
conn.connect();
inputStream = conn.getInputStream();
long file_length = conn.getContentLength();
int len;
int total_length = 0;
byte[] data = new byte[1024];
while ((len = inputStream.read(data)) != -1) {
total_length += len;
int value = (int) ((total_length / (float) file_length) * 100);
publishProgress(value);
outputStream.write(data, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return "-1";
} finally {
if (inputStream != null) {
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return "-1";
}
}
}
return "0";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
progress_info.setText("已下载:"+values[0]+"%");
if (values[0]==100){
progress_info.setText("下载完成,准备安装!");
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File fileLocation = new File(context.getFilesDir(), "xxx.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(fileLocation),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
initPopUpWindow();
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}</pre>
初始化UI界面:
private void initPopUpWindow(){
PopupWindow popupWindow = new PopupWindow(context);
popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
View view=LayoutInflater.from(context).inflate(R.layout.layout_popupwindow_style, null);
progressBar= (ProgressBar) view.findViewById(R.id.progress_horizontal);
progress_info= (TextView) view.findViewById(R.id.progress_info);
popupWindow.setContentView(view);
popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(((Activity)context).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
}
执行任务:
new DownloadTask().execute(url);
//url apk下载地址