异步任务可以在工作线程中完成数据处理,并在主线程总更新UI,其使用简单,这里不做介绍。
我们从无参构造函数开始分析:
public AsyncTask() {
this((Looper) null);
}
/**
初始化了mHandler、mWorker、mFuture
**/
public AsyncTask(@Nullable Looper callbackLooper) {
//因为无参构造函数中传入了null,所以这里的mHandler = getMainHandler(),后面的线程切换就是使用这里的mHandler
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
发现里面只是初始化了mHandler、mWorker、mFuture。
接下来分析AsyncTask.execute()方法:
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,Params... params) {
//这里可以看出同一AsyncTask对象如果多次运行就回抛出异常
//如果要多次调用就势必需要重置AsyncTask对象中一些标识,这样还不如直接NEW一个,所以不允许一个AsyncTask多次运行(我猜的)
if (mStatus != AsyncTask.Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = AsyncTask.Status.RUNNING;
// onPreExecute 方法在这里被调用
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
首先我们找到了为什么同一个AsyncTask对象不可多次运行,代码中注释已经写出来了。
然后找到了onPreExecute()方法的调用地方,这里要注意,到onPreExecute方法执行为止还没有出现任何线程切换,所以onPreExecute方法是运行在原线程上的,即调用AsyncTask.execute()的线程。注意如果我们在子线程中调用new AsyncTask().execute() ,并且在onPreExecute()方法中执行了修改UI的代码,就会报错(不能在子线程中修改UI)
之后mWorker.mParams保存了params,然后执行exec.execute(mFuture); 这个行代码看起来是不是很像线程池的调用啊?我们去找一下exec。
exec为sDefaultExecutor,是由参数传入的。
贴出exec的代码:
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
//定义了新的Runnable,下面会被执行,就切换到了子线程执行了
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
看到exec的最终是由SerialExecutor实现。
在SerialExecutor中定义了一个队列ArrayDeque,每次都创建一个新Runnable放在队尾。
首次进入由于mActive为null,则调用了scheduleNext()
scheduleNext方法中从队列中获取队首的runnable赋值给mActive,并且在THREAD_POOL_EXECUTOR中执行了这个runnable,看上面定义的Runnable的run方法,是用try finally代码块包裹的,即执行网r.run后还是会执行scheduleNext(),这样就可以执行完队列中的所有任务了。
然后我们从r.run()往回看,r是由参数传进来的,r就是无参构造函数中初始化的mFuture。mFuture.run即为mWorker.call,回上面看一下call方法,其中就调用了result = doInBackground(mParams);这样doInBackground就再子线程中运行了。
继续查看mWorker.call方法,执行完了doInBackground,最终会调用postResult(result);
查看postResult(result);方法:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private Handler getHandler() {
return mHandler;
}
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
这里的代码就很简单了,将结果用整个用handler切换线程。mHandler是在无参构造函数中初始化的即getMainHandler方法。
查看InternalHandler代码:
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
//doInBackground 完成 ,需要调用onPostExecute
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
//跟新进度方法onProgressUpdate
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
result是由上面的mHandle发送过来的,其实是AsyncTaskResult类:
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
result.mTask.finish(result.mData[0]);
查看上面的 Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
即result.mTask为this,也就是当前的AsyncTask,所以即为this.finish();
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = AsyncTask.Status.FINISHED;
}
最终在主线程中检查,如果已经取消则调用onCancelled,否则onPostExecute。将标识改为FIINISHED.