AsyncTask使用總結(jié)和源碼分析

簡介

當(dāng)android應(yīng)用啟動的時候會啟動一條主線程,這個主線程負(fù)責(zé)向UI組件分發(fā)事件(包括繪制事件),所以當(dāng)在主線程執(zhí)行耗時任務(wù)你都會阻塞UI線程導(dǎo)致事件停止分發(fā)(包括繪制事件),如果UI線程blocked的時間太長(大約超過5秒),用戶就會看到ANRapplication not responding)的對話框,所以當(dāng)我們執(zhí)行耗時任務(wù)的時候要在子線程來做(訪問網(wǎng)絡(luò)、數(shù)據(jù)庫查詢等等),所以主線程和子線程的通信就成為了關(guān)鍵,android提供了handler可以讓主線程和子線程通信,其中AsyncTask是通過handler和線程池來實(shí)現(xiàn)的輕量化異步任務(wù)的工具。(以下所有源碼來自23版本)

用法

可以看下AsyncTask類的簡化代碼

public abstract class AsyncTask<Params, Progress, Result> {

   abstract Result doInBackground(Params... params);

    void onPreExecute() {}

    protected void onProgressUpdate(Progress... values) {}

    protected void onPostExecute(Result result) {}
}

可以看到AsyncTask是個抽象類,有個唯一的抽象方法是doInBackground和三個泛型Params, Progress, Result,三個泛型分別是doInBackground,onProgressUpdate,onPostExecute方法的形參類型。實(shí)現(xiàn)AsyncTask一般要實(shí)現(xiàn)代碼中的那幾個方法,現(xiàn)在讓我們看看這幾個方法的用處。

  • doInBackground(Params... params):
    就像它的名字那樣,是在子線程執(zhí)行的,所以耗時任務(wù)寫這里面
  • onPreExecute():
    在execute(Params... params)被調(diào)用后立即執(zhí)行,一般用來在執(zhí)行后臺任務(wù)前對UI做一些標(biāo)記,在主線程執(zhí)行
  • onProgressUpdate(Progress... values):
    在調(diào)用publishProgress(Progress... values)時,此方法被執(zhí)行,直接將耗時任務(wù)進(jìn)度信息更新到UI組件上,在主線程執(zhí)行
  • onPostExecute(Result result):
    當(dāng)后臺異步任務(wù)結(jié)束,此方法將會被調(diào)用,result為doInBackground返回的結(jié)果,在主線程執(zhí)行

在實(shí)現(xiàn)完AsyncTask抽象類后調(diào)用execute(Params... params)方法來執(zhí)行異步任務(wù)。

注意事項(xiàng)

  • 當(dāng)AsyncTask為非靜態(tài)內(nèi)部類時,AsyncTask實(shí)例會帶有activity的引用,當(dāng)activity銷毀時AsyncTask后臺線程還在執(zhí)行,會導(dǎo)致Activity無法被回收,引起內(nèi)存泄露。
  • AsyncTask的版本差異問題,版本實(shí)現(xiàn)AsyncTask的線程池會有所不一樣,這樣導(dǎo)致版本之中執(zhí)行AsyncTask的效果不同,可能需要因?yàn)檫@個做版本兼容。
    在Android 1.6到2.3是并行的,有5個核心線程的線程池(ThreadPoolExecutor)負(fù)責(zé)調(diào)度任務(wù)。但Android 3.0開始,AsyncTask改成了串行,默認(rèn)的Executor被指定為SERIAL_EXECUTOR。不過可以通過executeOnExecutor()方法自己傳入線程池來實(shí)現(xiàn)并行,也可以調(diào)用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,...)利用AsyncTask.THREAD_POOL_EXECUTOR這個AsyncTask自己實(shí)現(xiàn)的線程池來實(shí)現(xiàn)并行任務(wù)。
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,        Params... params){...}

源碼分析

因?yàn)檎{(diào)用execute方法來執(zhí)行異步任務(wù),我們先從execute方法來分析。

public enum Status {
    /**     * Indicates that the task has not been executed yet.     */
    PENDING,
    /**     * Indicates that the task is running.     */
    RUNNING,
    /**     * Indicates that {@link AsyncTask#onPostExecute} has finished.     */
    FINISHED,
}

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    return executeOnExecutor(sDefaultExecutor, params);
}

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;
}

看到execute實(shí)際是調(diào)用了executeOnExecutor()傳進(jìn)去了sDefaultExecutor的默認(rèn)線程池,當(dāng)調(diào)用了executeOnExecutor時,mStatus (默認(rèn)是PENDING)如果不是PENDING就會拋出異常,而且在這個方法里面mStatus會賦值成RUNNING(所以execute方法只能執(zhí)行一次)。
然后就執(zhí)行onPreExecute方法(上面講過這是執(zhí)行前做的準(zhǔn)備工作),最后調(diào)用exec.execute(mFuture);執(zhí)行線程任務(wù)。
要知道怎么執(zhí)行線程池任務(wù)要看sDefaultExecutor代碼。

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

public static final Executor THREAD_POOL_EXECUTOR
        = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 
               TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

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);
        }
    }
}

sDefaultExecutor 實(shí)際上就是SerialExecutor ,SerialExecutor 實(shí)現(xiàn)了Executor 接口,在執(zhí)行execute,任務(wù)加入了ArrayDeque數(shù)組,mActive是當(dāng)前在執(zhí)行的任務(wù),執(zhí)行的任務(wù)會加入THREAD_POOL_EXECUTOR線程池里執(zhí)行,可以看到當(dāng)前有任務(wù)執(zhí)行時,不會執(zhí)行這個任務(wù),而且mTasks會循環(huán)的把加入的任務(wù)串行的一個一個的執(zhí)行完。
那么一個異步任務(wù)是如果個個步驟的一次調(diào)用的?首先回到構(gòu)造方法來看下:

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);
        }
    };
    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);
            }
        }
    };
}

mFuture就是上面看到的線程池執(zhí)行的任務(wù)(future基本用處可以看這里Future),當(dāng)mFuture被SerialExecutor執(zhí)行時,會執(zhí)行其mWorker。它在調(diào)用的時候,先把mTaskInvoked設(shè)置為true表示已調(diào)用,設(shè)置線程優(yōu)先級,然后才執(zhí)行doInBackground()方法,并執(zhí)行postResult發(fā)送其返回的結(jié)果。postResult代碼如下:

private Result postResult(Result result) {
    @SuppressWarnings("unchecked")
    Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
            new AsyncTaskResult<Result>(this, result));
    message.sendToTarget();
    return result;
}

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

postResult利用getHandler獲取到Handler 然后發(fā)標(biāo)記為MESSAGE_POST_RESULT的消息和doInBackground返回的Result給InternalHandler,
InternalHandler代碼如下:

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;
        }
    }
}

可以看到InternalHandler 有兩種消息,一種是MESSAGE_POST_PROGRESS用來調(diào)用onProgressUpdate方法的,也就是之前說的更新進(jìn)度方法,另外是MESSAGE_POST_RESULT,調(diào)用了finish方法。

private void finish(Result result) {
    if (isCancelled()) {
        onCancelled(result);
    } else {
        onPostExecute(result);
    }
    mStatus = Status.FINISHED;
}

isCancelled是判斷當(dāng)前task是否取消了,取消了就調(diào)用onCancelled方法來回調(diào)result,沒取消就調(diào)用onPostExecute返回result。
整個流程就到這里了。

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

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