Android AsyncTask源碼解析

近兩天有點(diǎn)閑,在逛主席的知識星球的時候看到了AsyncTask這個知識點(diǎn),在這里強(qiáng)烈推薦下郭嬸寫的AsyncTask一篇文章:https://blog.csdn.net/guolin_blog/article/details/11711405,筆者當(dāng)時就是跟著這篇文章來學(xué)習(xí)AsyncTask的。今天我們一起對AsyncTask的源碼進(jìn)行分析下,加深下自己的理解。

照例,我們先來看下AsyncTask的定義:

   private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{

        @Override     //后臺任務(wù)開始之前調(diào)用,進(jìn)行界面初始化操作
        protected void onPreExecute() {       
            super.onPreExecute();
        }

        @Override      //處理耗時操作
        protected Boolean doInBackground(String... params) {
            return null;
        }

        @Override      //后臺任務(wù)執(zhí)行完畢后回調(diào),可進(jìn)行UI操作
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
        }

        @Override     //當(dāng)在doInBackground方法中調(diào)用publishProgress方法后會回調(diào)該方法,執(zhí)行進(jìn)度更新操作
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
    }

由于AsyncTask類是一個抽象類,所以我們需要定義一個類MyAsyncTask繼承自AsyncTask,在這里需要指定三個泛型參數(shù):第一個泛型參數(shù)為執(zhí)行當(dāng)前AsyncTask需要傳入的參數(shù),第二個泛型參數(shù)為進(jìn)度更新的類型,第三個泛型參數(shù)為后臺任務(wù)執(zhí)行的返回類型??梢钥吹剑覀冎貙懥薃syncTask中四個常用的方法,分別為:onPreExecute、doInBackground、onPostExecute、onProgressUpdate。在上述四個方法中,除了doInBackground方法運(yùn)行在工作線程,其他三個方法都是運(yùn)行在UI線程中的。

接著我們就可以使用MyAsyncTask了,使用方式很簡單,只需要調(diào)用execute方法即可:

new MyAsyncTask().execute("test");

關(guān)于AsyncTask的基本操作就介紹完畢了,接下來我們一起分析下AsyncTask的源碼,首先看下它的構(gòu)造函數(shù):

    #AsyncTask
    public AsyncTask(@Nullable Looper callbackLooper) {
        //1.在這里我們傳入的callbackLooper為null,所以會直接調(diào)用到getMainHandler方法,
        //創(chuàng)建InternalHandler實(shí)例sHandler,并賦值給mHandler
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        //2.創(chuàng)建WorkerRunnable實(shí)例對象mWorker
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

        //3.創(chuàng)建 FutureTask實(shí)例mFuture,并將2處的 mWorker賦值給 mFuture對象的成員變量callable
        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);
                }
            }
        };
    }

我們跟進(jìn)去 1處的getMainHandler方法看下:

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

可以看到,在getMainHandler方法中創(chuàng)建了InternalHandler實(shí)例sHandler,并綁定到UI線程。

AsyncTask的構(gòu)造方法分析完畢了,我們接著從AsyncTask的入口execute方法繼續(xù)分析,跟進(jìn)去execute方法看下:

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

可以看到,execute方法內(nèi)部直接調(diào)用到executeOnExecutor方法,將sDefaultExecutor和params參數(shù)直接傳入,sDefaultExecutor是個什么東西呢?我們一起看下它的定義:

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    
    /**
     * An {@link Executor} that executes tasks one at a time in serial
     * order.  This serialization is global to a particular process.
     */
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

簡單理解,sDefaultExecutor就是一個SerialExecutor實(shí)例對象,需要注意的是,該實(shí)例對象為static類型的,歸屬于AsyncTask類,也就是說無論我們創(chuàng)建多少AsyncTask實(shí)例對象,在AsyncTask類中僅存在一個SerialExecutor實(shí)例。

好了,我們回過頭繼續(xù)跟進(jìn)去executeOnExecutor方法:

    @MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        //1.對當(dāng)前AsyncTask對象的狀態(tài)進(jìn)行判斷,
        //每一個AsyncTask實(shí)例只能調(diào)用一次execute方法
        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)");
            }
        }
        //2.將當(dāng)前AsyncTask的狀態(tài)標(biāo)記為RUNNING
        mStatus = Status.RUNNING;
        //3.調(diào)用到onPreExecute方法,進(jìn)行界面初始化操作
        onPreExecute();
        //4.將params參數(shù)賦值給mWorker的成員變量mParams
        mWorker.mParams = params;
        //5.調(diào)用SerialExecutor對象的execute方法,將mFuture作為參數(shù)傳入
        exec.execute(mFuture);

        return this;
    }

這里我們先來看下Status這個類,Status為枚舉類,定義了AsyncTask的三種狀態(tài),分別為PENDING(初始化狀態(tài),表示當(dāng)前任務(wù)還未被執(zhí)行)、RUNNING(當(dāng)前任務(wù)正在執(zhí)行)、FINISHED(當(dāng)前任務(wù)執(zhí)行完畢):

    /**
     * Indicates the current status of the task. Each status will be set only once
     * during the lifetime of a task.
     */
    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,
    }

好了,我們回過頭繼續(xù),5處調(diào)用到SerialExecutor對象的execute方法,將mFuture作為參數(shù)傳入,我們跟進(jìn)去看下:

    private static class SerialExecutor implements Executor {
        //定義ArrayDeque隊(duì)列mTasks,用于存儲Runnable實(shí)例
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        //mActive表示當(dāng)前正在執(zhí)行的任務(wù)Runnable
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            //1.入隊(duì)操作
            mTasks.offer(new Runnable() {
                public void run() {        
                    try {
                        //線程池中執(zhí)行
                        r.run();         
                    } finally {
                        //3.當(dāng)前任務(wù)執(zhí)行完畢后,則會調(diào)用scheduleNext方法執(zhí)行下一項(xiàng)任務(wù)
                        scheduleNext();
                    }
                }
            });
            //2.對mActive進(jìn)行null判斷,如果當(dāng)前沒有正在執(zhí)行的任務(wù),會立刻調(diào)用scheduleNext方法執(zhí)行首項(xiàng)任務(wù)
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

SerialExecutor實(shí)現(xiàn)了Executor接口,該類用于串行執(zhí)行任務(wù)??梢钥吹皆赟erialExecutor的execute方法中,對每一個AsyncTask對應(yīng)的mFuture實(shí)例都會創(chuàng)建一個Runnable類型的匿名對象,并將該Runnable對象插入到mTasks隊(duì)列的末尾。接著在2處對mActive進(jìn)行null判斷,如果當(dāng)前沒有正在執(zhí)行的任務(wù),會立刻調(diào)用scheduleNext方法執(zhí)行首項(xiàng)任務(wù)。

顯而易見,任務(wù)的執(zhí)行重點(diǎn)在于scheduleNext方法,從上述代碼可以看到,在scheduleNext方法中會調(diào)用mTasks.poll方法進(jìn)行出隊(duì)操作,刪除并返回隊(duì)頭的Runnable對象,并將該Runnable對象賦值給mActive,如果該Runnable對象不為空,那么就將其作為參數(shù)傳遞給THREAD_POOL_EXECUTOR的execute方法進(jìn)行執(zhí)行。THREAD_POOL_EXECUTOR是個什么東西呢?那還用說嗎,肯定是線程池?。?/p>

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR;

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        //重點(diǎn),賦值操作
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

關(guān)于ThreadPoolExecutor構(gòu)造方法各個參數(shù)的含義,相信大家都了解,在這里不是本文的重點(diǎn),筆者就略過了。

我們回到Runnable匿名對象的run方法中看下,需要注意的是,該run方法中的所有操作均在子線程中,可以看到在Runnable對象的run方法中,直接調(diào)用到r.run()方法,大家還記得r是什么嗎?r就是我們調(diào)用SerialExecutor的execute方法傳入的mFuture對象(AsyncTask構(gòu)造方法中對其完成的實(shí)例化)。我們跟進(jìn)去看下:

    #FutureTask
    public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            //1.callable實(shí)質(zhì)為AsyncTask構(gòu)造方法中創(chuàng)建的mWorker對象
            //在AsyncTask構(gòu)造方法中創(chuàng)建FutureTask對象時將mWorker作為參數(shù)傳入,
            //賦值給FutureTask對象的callable成員變量,并將state置為NEW
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //2.重點(diǎn) 調(diào)用到mWorker對象的call方法
                    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);
        }
    }

我們跟進(jìn)去mWorker的call方法看下:

    #AsyncTask構(gòu)造方法中
    mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                //定義Result局部變量,接收后臺任務(wù)返回的結(jié)果
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //1.重點(diǎn)  調(diào)用到AsyncTask的doInBackground方法,執(zhí)行耗時操作
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    //2.重點(diǎn) 調(diào)用postResult方法,將后臺任務(wù)執(zhí)行的結(jié)果result作為參數(shù)傳入
                    postResult(result);
                }
                return result;
            }
        };

我們跟進(jìn)去2處的postResult方法看下:

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

可以看到在postResult方法中首先將后臺任務(wù)執(zhí)行的結(jié)果result封裝成AsyncTaskResult實(shí)例,接著通過handler發(fā)送了一條MESSAGE_POST_RESULT的Message。我們跟進(jìn)去getHandler方法看下:

    private Handler getHandler() {
        return mHandler;
    }

getHandler方法中直接將mHandler return掉了,不知道大家還記不記得,mHandler其實(shí)就是InternalHandler實(shí)例對象,在AsyncTask的構(gòu)造方法中完成的賦值。好了,接下來我們看下InternalHandler的handleMessage方法:

    private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {     //執(zhí)行在主線程
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    //重點(diǎn),調(diào)用result.mTask.finish方法,將后臺返回的result作為參數(shù)傳入;result.mTask就是當(dāng)前AsyncTask實(shí)例
                    //實(shí)質(zhì)調(diào)用到當(dāng)前AsyncTask對象的finish方法,將后臺返回的result作為參數(shù)傳入
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    //用于處理進(jìn)度更新操作
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

接著我們跟進(jìn)去AsyncTask的finish方法中看下:

    private void finish(Result result) {
        //判斷當(dāng)前任務(wù)是否取消
        if (isCancelled()) {
            //執(zhí)行AsyncTask的onCancelled方法
            onCancelled(result);
        } else {
            //執(zhí)行AsyncTask的onPostExecute方法
            onPostExecute(result);
        }
        //將當(dāng)前AsyncTask的狀態(tài)置為FINISHED
        mStatus = Status.FINISHED;
    }

到這里,AsyncTask的源碼分析就結(jié)束了,希望本文可以幫助到學(xué)習(xí)AsyncTask的小伙伴。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容