AsyncTask在安卓中常用于線程間通信外傅。在子線程執(zhí)行耗時(shí)任務(wù),在主線程更新UI蒜危。
AsyncTask內(nèi)部封裝了Handler和線程池墨技。
1、AsyncTask主要靠InternalHandler去跟主線程通信邪蛔,InternalHandler繼承自Handler類急黎,在handleMessage方法里面處理了消息扎狱。
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;
}
}
}
2、有兩個(gè)線程池THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR
SERIAL_EXECUTOR負(fù)責(zé)隊(duì)列管理勃教,負(fù)責(zé)執(zhí)行任務(wù)的是THREAD_POOL_EXECUTOR
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
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);
}
}
}
回過頭來(lái)淤击,咱們?cè)賮?lái)看看executeOnExecutor方法
@MainThread
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);
return this;
}
這個(gè)方法里面做了下狀態(tài)判斷和狀態(tài)修改,所以可以看出故源,一個(gè)AsyncTask實(shí)例只能執(zhí)行一次污抬。然后分別調(diào)用了onPreExecute和exec.execute(mFuture),這里的exec就是SERIAL_EXECUTOR绳军,調(diào)用exec.execute(mFuture)就是把任務(wù)插入到任務(wù)隊(duì)列中印机。然后依次執(zhí)行任務(wù)。