AsyncTask是一个轻量级的异步任务类。它可以在线程池中执行耗时的后台任务。然后把执行的进度和结果传递给主线程并且在主线程中更新UI。
AsyncTask基本介绍
本身是一个抽象类:
public abstract class AsyncTask<Params, Progress, Result> {}
其中参数如下:
泛型 | 意义 |
---|---|
Params | 异步任务的入参,比如下载图片时传入String类型的url |
Progress | 任务执行的进度 |
Result | 任务的执行结果 |
几个常用的方法介绍如下:
void onPreExecute() :
任务开启前的准备,设置UI的状态等(位于主线程)Result doInBackground(Params...param) :
开启子线程执行后台任务,Params就是三个泛型中的第一个;Result为任务执行的返回值当作参数传入onPostExecute()函数(位于子线程)void onPostExecute(Result result) :
任务执行完毕后回调此方法,可在这里进行UI更新等(位于主线程)void onProgressUpdate(Progress... values) :
任务执行的过程中进行进度更新,参数即为泛型的第二个(位于主线程)publishProgress(PROGRESS_MAX, maxLen):
在后台任务执行过程中调用此方法会调用onProgressUpdate()方法对UI进行更新
使用方法:
new AsyncTask().execute(Params);
AsyncTask使用的条件限制
- 必须在主线程中创建
- execute方法必须在UI线程中调用
- 不要在程序中直接调用一系列方法doInBackground等
- 一个对象只能执行一次,即只能调用一次execute方法
AsyncTask源码简单介绍
大致的流程如下图(比较简陋,有很多没有提及的地方):
接下来我列出我认为相对重要的方法:
- 构造方法
实例化mWorker/mFuture,并将两者绑定。
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
this((Looper) null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Handler handler) {
this(handler != null ? handler.getLooper() : null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
// 实例化Callable
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority