AsyncTask是android中封装的一个用于异步操作的线程类,可直接定义内部类,比起handler较为简洁方便。使用方法如下:
1.新建一个类(通常定义内部类)继承自AsyncTask。范式中的三个参数类型分别对应类中回调函数传递的参数类型,可自定义参数类型。
class MainTask extends AsyncTask<String, Integer, Bitmap> {// 继承AsyncTask
// 处理后台执行的任务,在另一个线程执行
@Override
protected Bitmap doInBackground(String... params) {
// 发送进度,将会调用onProgressUpdate(Integer... progress)方法
publishProgress(0);
// 处理代码。。。
publishProgress(30);
// 处理代码。。。
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
publishProgress(100);
// 返回Bitmap类型的数据,完成后将调用onPostExecute(Bitmap... result)方法
return bmp;
}
// 在调用publishProgress之后被调用,在主线程执行
protected void onProgressUpdate(Integer... progress) {
System.out.println(progress[0]);// 进度
}
// 后台任务执行完之后被调用,在主线程执行
protected void onPostExecute(Bitmap result) {
if (result != null) {
System.out.println("success");
} else {
System.out.println("fail");
}
}
// 在doInBackground(Params...)之前被调用,在主线程执行
protected void onPreExecute() {
}
// 在主线程执行,后台线程停止之后
protected void onCancelled() {
}
}
2.在类中实例化AsyncTask对象,调用execute()方法即可。
MainTask task = new MainTask();
task.execute("url");
注意点:task对象只能运行一次,若想重新运行后台线程,需重新实例化AsyncTask对象。execute()方法中的参数对应doInbackground()中传入的参数。