上一篇我们分析了Handler的源码,这一篇我们来看一下AsyncTask,AsyncTask本身也是通过Handler,Message的机制来实现的。具体的实现方式,我们来看源码。
public AsyncTask() {
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(result);
}
};
mFuture = new FutureTask(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);
}
}
};
}
在构造函数中,我们先看到了构造了mWorker,再通过mWorker再构造了一个mFuture,就没有其他的了,这两个对象是用来干什么的先放在这里,稍后会看到。在我们想要执行AsyncTask的时候就需要我们执行execute,我们再从这个方法看起:
public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
直接委托给executeOnExecutor来处理
public final AsyncTask executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != 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 = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
这里我们看到了onPreExecute()的执行,这里也证明了为什么AsyncTask必须在UI线程中创建。再需要我们找的就是和是调用了doInBackground,exec是传入的sDefaultExecutor,sDefaultExecutor是SERIAL_EXECUTOR,是
SerialExecutor()对象,exec.execute(mFuture),会执行r.run();也就是mFuture的run方法;
Executor sDefaultExecutor = SERIAL_EXECUTOR;
Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor {
final ArrayDeque mTasks = new ArrayDeque();
Runnable mActive;
public synchronized void execute(final Runnable r) {
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);
}
}
}
这里是FutureTask的run方法
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
记得我们在构造mFutureTask的时候传入了WorkerRunnable的对象,就是mWorker。这里的callable就是mWorker,c.call调用的就是mWorker.call。
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
我们再回到AsyncTask的构造函数里,mWorker.call里我们看到了doInBackground(mParams),这里我们看到了指定的第三个泛型Result result,作为执行后的结果 postResult(result)
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
到这里就是我们比较熟悉的发送Message到Handler,拿到的Handler是
sHandler = new InternalHandler();
处理消息的过程自然是在InternalHandler的handleMessage里
public void handleMessage(Message msg) {
AsyncTaskResult> result = (AsyncTaskResult>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
我们可以想象到MESSAGE_POST_RESULT 对应的就是处理完成的Message,而MESSAGE_POST_PROGRESS就是处理过程中,标示进度的消息,而发送这条消息的地方就是在publishProgress
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult
finish里一定就是onPostExecute,忘了还有onCancelled
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
整个过程我们就分析完了,AsyncTask的本质还是thread + handler message 实现的,我们也可以理解为什么创建AsyncTask为什么一定要在UI线程中。