今天偶然想到了使用AsyncTask异步任务栈,可以在onPostExecute()中修改UI,这不是一个很奇怪的现象吗?于是便萌发想法看看源码这到底是怎么回事。
一、AsyncTask的使用介绍
还记得AsyncTask的使用方法不?主要是重写几个方法
protected void onPreExecute() //开始前
protected void onProgressUpdate() //进行中
protected Object doInBackground() //后台执行的具体逻辑
protected void onPostExecute() //任务执行完毕
protected void onCancelled() //任务取消
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
@Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
return mFakeImageLoader.getImage();
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.progress.setVisibility(View.GONE);
v.icon.setVisibility(View.VISIBLE);
v.icon.setImageBitmap(result);
}
}
}.execute(holder);
二、源码中找答案
-
AsyncTask在其中打开Structure视图,马上就看到了有个getHandler()方法还有一个成员变量InternalHandler。于是马上猜测AsyncTask,其实是使用了Handler机制实现了线程切换。
继续看InternalHandler的源码,已经发现端倪,它已经直接调用了onProgressUpdate()方法。
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
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;
}
}
}
- finish方法里有什么呢?继续看,果然调用onPostExecute()方法,至此,基本已经确定AsyncTask能够在回调中修改UI就是使用了Handler机制。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
- 什么时候向Handler发的消息呢?看AsyncTask构造方法就可以了。构造方法里初始化了工作线程和FutureTask。
public AsyncTask() {
//创建一个工作线程
mWorker = new WorkerRunnable<Params, Result>() {
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); //执行完了调用postResult
}
};
//放入FutureTask中
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);
}
}
};
}
- 在executeOnExecutor方法中开始执行。
public final AsyncTask<Params, Progress, Result> 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); //exec是传入的线程池
return this;
}
- 最后看下第4步中的postResult()方法的源码,找到怎么给Handler发消息的。到这里整个链条已经串起来。
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget(); //发送消息
return result;
}
三、总结
AsyncTask并没有违反Android定义的非UI线程不能修改UI的规则,实际上它是使用了Handler机制实现了线程切换。在onPostExecute() 实际上已经处于UI线程当中,所以可以对UI进行修改,同理于onProgressUpdate()方法。