AsyncTask(基于Api25) 源碼分析

介紹:

AsyncTask是一種輕量級(jí)的異步任務(wù)類,它可以在線程池中執(zhí)行后臺(tái)任務(wù),然后把執(zhí)行的進(jìn)度和最終結(jié)果傳遞給主線程并在主線程中更新UI。
AsyncTask是一個(gè)抽象的泛型類,它提供了Params,Progress和Result這三個(gè)泛型參數(shù),其中Params表示參數(shù)的類型,Progress表示后臺(tái)任務(wù)的執(zhí)行進(jìn)度的類型,而Result則表示后臺(tái)任務(wù)的返回結(jié)果的類型,如果AsyncTask確實(shí)不需要傳遞具體的參數(shù),那么這三個(gè)泛型參數(shù)可以用Void來(lái)代替。AsyncTask這個(gè)類的生命如下:
public abstract class AsyncTask<Params, Progress, Result>

核心方法
  1. protected void onPreExecute()
    在AsyncTask被調(diào)用的線程中執(zhí)行,在異步任務(wù)執(zhí)行之前被調(diào)用
  2. protected abstract Result doInBackground(Params... params)
    在線程池中執(zhí)行,執(zhí)行異步任務(wù),并返回其結(jié)果,params參數(shù)表示異步任務(wù)的輸入?yún)?shù)。在此方法中可以通過(guò)publishProgress方法來(lái)更新任務(wù)的進(jìn)度,publishProgress會(huì)發(fā)送消息間接調(diào)用onProgressUpdate方法
  3. protected void onProgressUpdate(Progress... values)
    在主線程中執(zhí)行,當(dāng)后臺(tái)任務(wù)的執(zhí)行進(jìn)度發(fā)生改變時(shí)調(diào)用此方法
  4. protected void onPostExecute(Result result)
    在主線程中執(zhí)行,在異步任務(wù)執(zhí)行完成之后,此方法被調(diào)用,其result參數(shù)是后臺(tái)任務(wù)的返回值

源碼分析

為了分析AsyncTask的源碼,我們從execute方法入手

//一個(gè)串行執(zhí)行任務(wù)的線程池
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

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只能被執(zhí)行一次
        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)");
            }
        }
        //將AsyncTask置為RUNNING狀態(tài)
        mStatus = Status.RUNNING;
        //此處調(diào)用onPreExecute方法
        onPreExecute();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }```
從代碼中看出,execute會(huì)調(diào)用executeOnExecutor方法,其中有這么兩行代碼:

mWorker.mParams = params;
exec.execute(mFuture);```
那這個(gè)mWorker 和mFuture是哪里來(lái)的呢?
接著往下看:

public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                //將AsyncTask設(shè)置為已調(diào)用
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //調(diào)用doInBackground方法
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    //最終調(diào)用postResult方法
                    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);
                }
            }
        };
    }```
原來(lái),在AsyncTask的構(gòu)造函數(shù)中,我們初就始化了mWorker 和mFuture變量,下面我們來(lái)看下這兩個(gè)變量,通過(guò)看源碼我們知道:
WorkerRunnable是一個(gè)封裝了Params參數(shù)的Callable抽象類
FutureTask是一個(gè)實(shí)現(xiàn)了Runnable和Future<V>的類
從上面,我們知道executeOnExecutor 會(huì)調(diào)用exec.execute(mFuture),其最終會(huì)執(zhí)行mFuture的run方法
下面讓我們來(lái)看看FutureTask的run方法

public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//在這里調(diào)用了從FutureTask構(gòu)造函數(shù)里傳進(jìn)來(lái)的mWorker的call方法
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
//最終會(huì)調(diào)用自身的done方法
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);
}
}

protected void set(V v) {
if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
outcome = v;
U.putOrderedInt(this, STATE, NORMAL); // final state
finishCompletion();
}
}
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (U.compareAndSwapObject(this, WAITERS, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
//最終調(diào)用mFuture的done方法
done();

    callable = null;        // to reduce footprint

}

從以上代碼我們可以分析出,mFuture的run方法會(huì)調(diào)用mWorker的call方法,并最終調(diào)用自己的done方法。
那我們接著看mWorker.call:

private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}

private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}```
在mWorker.call中,我們調(diào)用了doInBackground方法,最終調(diào)用postResult
在上面的代碼中,postResult方法會(huì)通過(guò)sHandler發(fā)送一個(gè)MESSAGE_POST_RESULT的消息,這個(gè)sHandler定義如下:

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;
            }
        }
}```
可以發(fā)現(xiàn),sHandler收到MESSAGE_POST_RESULT消息后會(huì)調(diào)用AsyncTask的finish方法,如下所示:

private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}```
AsyncTask的finish方法邏輯比較簡(jiǎn)單,若果AsyncTask被取消了,那么久調(diào)用onCancelled方法,否則就會(huì)調(diào)用onPostExecute方法。
總結(jié)下來(lái),AsyncTask的大致執(zhí)行流程為:
AsyncTask.execute--->AsyncTask.executeOnExecutor
--->AsyncTask.onPreExecute--->mFuture.run--->mWorker.call
--->AsyncTask.doInBackground--->AsyncTask.postResult--->AsyncTask.finish
--->AsyncTask.onPostExecute or AsyncTask.onCancelled
--->mFuture.done
到這里AsyncTask的源碼就分析完成了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容