流行框架源碼分析(2)-AsynTask源碼分析

主目錄見:Android高級(jí)進(jìn)階知識(shí)(這是總目錄索引)
?國(guó)慶的假期剛剛過去,今天就用一篇比較簡(jiǎn)單的文章來收收心,AsynTask相信大家已經(jīng)非常熟悉了,而且用的也是溜溜地,但是他的源碼還是非常值得一看的,今天我們就一起來領(lǐng)略他的風(fēng)采吧。

假期結(jié)束

一.目標(biāo)

AsynTask內(nèi)部簡(jiǎn)化了Thread+handler的使用,可以讓我們?cè)诤笈_(tái)執(zhí)行任務(wù)并更新UI,但是這個(gè)開源框架經(jīng)過了幾次改版,代碼都有稍微變化,今天我們來分析這個(gè)源碼有兩個(gè)目標(biāo):
1)加深Thread+Handler的結(jié)合使用;
2)熟悉FutureTask的使用;
3)能解決用這個(gè)框架出現(xiàn)的一些問題.

二.源碼分析

要分析源碼我們都是老規(guī)矩,先來看看他的基本用法是什么:

public class DownloadTask extends AsyncTask<String,Integer,String> {
    private static final String TAG = "DOWNLOAD_TASK";
    private String name = "DownloadTask";
    public DownloadTask(String name){
        super();
        this.name = name;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //下載前
    }
    @Override
    protected String doInBackground(String... strings) {
        //后臺(tái)執(zhí)行
        try{
            Thread.sleep(3000);
        }catch (Exception e){
            e.printStackTrace();
        }
        return name;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //執(zhí)行完畢
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log.e(TAG, result + "execute finish at "+df.format(new Date()));
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        //當(dāng)前的進(jìn)度
    }
}

1)首先我們先來介紹AsyncTask<String,Integer,String>這其中的幾個(gè)參數(shù)作用
?1.第一個(gè)參數(shù)Params:在執(zhí)行調(diào)用excute時(shí)候傳入,在doInBackground()方法中使用。
?2.第二個(gè)參數(shù)Progress:后臺(tái)任務(wù)執(zhí)行時(shí)候,需要顯示進(jìn)度的時(shí)候,使用這里泛型作為返回參數(shù),在onProgressUpdate()方法中使用。
?3.第三個(gè)參數(shù)Result:當(dāng)任務(wù)執(zhí)行完畢時(shí)候?qū)Y(jié)果進(jìn)行返回,則使用這個(gè)指定的泛型來作為返回參數(shù),在onPostExecute()方法中使用。

2)接著我們就介紹這里面的幾個(gè)方法,來分別實(shí)現(xiàn)我們的需求:
?1.onPreExecute:這個(gè)方法是在后臺(tái)任務(wù)執(zhí)行開始之前,在這里一般會(huì)做一些初始化的工作。
?2.doInBackground(Params...):這個(gè)方法會(huì)在子線程中執(zhí)行,主要用于執(zhí)行一些耗時(shí)的任務(wù),其中方法的返回值類型是依據(jù)最后一個(gè)參數(shù)Result而定的,注意如果要更新進(jìn)度則調(diào)用publishProgress(Progress...)方法。
?3.onProgressUpdate(Progress...):當(dāng)執(zhí)行了publishProgress()方法之后,就會(huì)調(diào)用這個(gè)方法,在這個(gè)方法里面我們就可以顯示我們的進(jìn)度了,這個(gè)方法是在主線程的所以可以更新UI。
?4.onPostExecute(Result):當(dāng)doInBackground執(zhí)行完畢return完之后,就會(huì)把值返回給這個(gè)方法,這個(gè)方法也是可以更新UI的,做一些收尾工作。

到這里,參數(shù)和方法都已經(jīng)說明完畢了,我們?nèi)绻褂镁涂梢灾苯诱{(diào)用這句:

 new DownloadTask("downloadtask#1").execute("");

1.AsyncTask 構(gòu)造方法

首先從使用我們可以看出,我們代碼要從構(gòu)造方法開始看:

 public AsyncTask() {
        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;
            }
        };

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

雖然代碼很長(zhǎng),但是不要被嚇到,其實(shí)就new出了兩個(gè)對(duì)象,第一個(gè)對(duì)象mWorker 其實(shí)是個(gè)Callable:

 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

而第二個(gè)對(duì)象mFuture 是個(gè)FutureTask,然后把這個(gè)Callbale對(duì)象傳進(jìn)FutureTask里面,最后執(zhí)行的時(shí)候會(huì)回調(diào)Callable對(duì)象里面的call方法。接著程序會(huì)調(diào)用execute進(jìn)行執(zhí)行,我們繼續(xù)往下看。

2.AsyncTask execute

我們直接看看execute做了些啥,內(nèi)心興奮,一定有無(wú)數(shù)珍寶:

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

我擦嘞,一臉悶逼,就一個(gè)方法,這么簡(jiǎn)單,我們只能往下挖了:

    @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è)方法才是我們的主方法,第一個(gè)參數(shù)是可以傳入自己的Executor,也可以傳入這個(gè)類里面的THREAD_POOL_EXECUTOR,為了實(shí)現(xiàn)并行,我們可以在外部這么用AsyncTask: asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Params... params);必須在UI線程調(diào)用此方法。然后我們看到代碼會(huì)往下調(diào)用到onPreExecute()方法,這個(gè)方法就是我們上面說的會(huì)在doInBackground()方法之前執(zhí)行。那么我們的doInBackground()方法在哪里執(zhí)行呢?我們往下看到程序會(huì)執(zhí)行exec.execute(mFuture),這里的exec是我們默認(rèn)傳進(jìn)來的sDefaultExecutor,我們找到sDefaultExecutor是什么先:

Executor

我們看到sDefaultExecutor其實(shí)模式的是SerialExecutor,那就是說我們程序會(huì)調(diào)用SerialExecutor的execute()方法:

    private static class SerialExecutor implements Executor {
//線性雙向隊(duì)列,存儲(chǔ)所有的Task
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//當(dāng)前正在執(zhí)行的Task
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
//將新的任務(wù)添加進(jìn)隊(duì)列中
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
//執(zhí)行task
                        r.run();
                    } finally {
//如果執(zhí)行完task則執(zhí)行下一個(gè)任務(wù),這里明顯體現(xiàn)了串行執(zhí)行的特征
                        scheduleNext();
                    }
                }
            });
//如果沒有任務(wù)在執(zhí)行,則直接進(jìn)入執(zhí)行
            if (mActive == null) {
                scheduleNext();
            }
        }
//從線性雙向隊(duì)列中取出任務(wù)進(jìn)行執(zhí)行
        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
//用Executor執(zhí)行task
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

從程序可以看出我們程序會(huì)執(zhí)行傳進(jìn)來Runnable的run方法,那么這里的Runnable其實(shí)就是我們前面?zhèn)鬟M(jìn)來的FutureTask,也就是說會(huì)執(zhí)行這個(gè)FutureTask的run方法,我們來看看:

 public void run() {
        if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
//如果不為空,且狀態(tài)是NEW則調(diào)用
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
//調(diào)用task的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);
        }
    }

從程序可以看出,程序會(huì)調(diào)用FutureTask的call方法,而這里的c就是callable對(duì)象,也就是傳進(jìn)來的WorkerRunnable,所以我們看WorkerRunnable的call方法干了啥:

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

可以看到我們這里執(zhí)行到了我們的doInBackground(),然后我們最后把結(jié)果傳給了postResult()方法。我們直接跟進(jìn)這個(gè)方法看下:

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

可以看到這里發(fā)送了一個(gè)消息攜帶了MESSAGE_POST_RESULT和一個(gè)AsyncTaskResult對(duì)象,這個(gè)AsyncTaskResult對(duì)象是什么呢?

   @SuppressWarnings({"RawUseOfParameterizedType"})
    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }

其實(shí)就是攜帶一個(gè)AsncTask和result,我們直接看到發(fā)送到的Handler,從getHandler跟進(jìn)去,我們找到最終跑到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;
            }
        }
    }

我們看到這里有兩個(gè)分支,我們的消息攜帶的是MESSAGE_POST_RESULT,所以我們的程序會(huì)走到result.mTask.finish(result.mData[0])。這個(gè)finish其實(shí)就是AsynTask的內(nèi)部方法:

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

只有特殊情況下會(huì)調(diào)用onCancelled方法,正常情況下都會(huì)調(diào)用onPostExecute()方法,這里是在Handler中調(diào)用的,所以是在UI線程中調(diào)用的,這也印證了前面說的。我們的WorkerRunnable的call執(zhí)行完畢后,就會(huì)執(zhí)行到FutureTask的done方法。

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

這個(gè)方法里面的get()就是callable對(duì)象(WorkerRunnable)返回的result,然后我們看postResultIfNotInvoked方法做了啥:

private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

wasTaskInvoked 這個(gè)標(biāo)志在mWorker初始化的時(shí)候已經(jīng)設(shè)置為true,所以這里postResult一般執(zhí)行不到。但是我們前面說到更新進(jìn)度,怎么這里就沒看見呢?我們說過更新進(jìn)度我們必須要手動(dòng)調(diào)用publishProgress才行,我們看這個(gè)方法做了啥:

 @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

我們看到這個(gè)方法也是發(fā)送一條消息,不過這時(shí)候標(biāo)志是MESSAGE_POST_PROGRESS,我們看到Handler里面:

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

這個(gè)方法會(huì)到handleMessage方法里面的onProgressUpdate方法,我們直接跟進(jìn)這個(gè)方法:

  @SuppressWarnings({"UnusedDeclaration"})
    @MainThread
    protected void onProgressUpdate(Progress... values) {
    }

這個(gè)方法就是給我們子類重寫的,我們就可以在這個(gè)地方來更新我們的精度。好了,我們的源碼講解就到這里了。
總結(jié):從我們分析看,我們AsynTask現(xiàn)在默認(rèn)是串行的,以前3.0版本之前是并行的,現(xiàn)在如果要實(shí)現(xiàn)并行也是可以的,而且也可以自己實(shí)現(xiàn)一個(gè)Executor這里面的線程池?cái)?shù)量,線程數(shù)都是可以自己設(shè)置,所以網(wǎng)絡(luò)上說的AsynTask的坑其實(shí)不是什么大問題,只要使用得當(dāng),好啦,了解了源碼,我相信不用再聽別人說:坑了

最后編輯于
?著作權(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)容