异步任务——AsyncTask
一、基本知识
- 构建AsyncTask子类的参数
AsyncTask<Params, Progress, Result>是一个抽象类,常用用于被继承,继承AsyncTask需要指定如下三个泛型参数:
Params:启动任务时输入参数的类型
Progress:启动后台任务中返回进度值的类型
Result:后台执行任务完成后返回结果类型
- 构建AsyncTask子类的回调方法
doInBackground:必须重写,异步执行后台线程将要完成的任务,异步操作主体
onPreExecute:执行后台耗时操作前被调用,通常用户完成一些初始化操作
onPostExecute:当doInBackground完成后,系统自动调用此方法,并将doInBackground方法返回的值传递给该方法
onProgressUpdate:在doInBackground方法中调用publishProgress方法更新任务的执行进度后,会触发该方法
- 方法调用流程
构建一个类继承自AsyncTask(参数后面再谈,最基本的是Void)
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.i("tag", "doInBackground");
return null;
}
@Override
protected void onPreExecute() {
Log.i("tag", "onPreExecute");
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
Log.i("tag", "onPostExecute");
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i("tag", "onProgressUpdate");
super.onProgressUpdate(values);
}
}
在MainActivity中启动该异步线程
MyAsyncTask task = new MyAsyncTask();
task.execute();
会发现没有onProgressUpdate方法的Log信息,是因为没有在doInBackground中调用publishProgress方法。
@Override
protected Void doInBackground(Void... params) {
Log.i("tag", "doInBackground");
onProgressUpdate();
return null;
}
二、AsyncTask异步加载网络图片
private static final String[] imageUrl = {
"http://hiphotos.baidu.com/vermouthtj/pic/item/7bf1cf1bb6cf6de5ae513373.jpg",
"http://b.hiphotos.baidu.com/zhidao/pic/item/dc54564e9258d1092285920fd758ccbf6c814d2c.jpg",
"http://img1.3lian.com/img013/v4/89/d/23.jpg" };
ImageLoadAsyncTask task = new ImageLoadAsyncTask();
task.execute(imageUrl[0], imageUrl[1], imageUrl[2]);
/**
* Params:String是线程运行的初始参数
* Progress:不需要一个加载进度,因此为Void
* Result:当线程结束后返回的数据
*
* @author 李波
*
*/
class ImageLoadAsyncTask extends AsyncTask<String, Void