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

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

假期結(jié)束

一.目標(biāo)

AsynTask內(nèi)部簡化了Thread+handler的使用葛峻,可以讓我們在后臺(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);
                }
            }
        };
    }

雖然代碼很長蜘欲,但是不要被嚇到,其實(shí)就new出了兩個(gè)對象晌柬,第一個(gè)對象mWorker 其實(shí)是個(gè)Callable:

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

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

2.AsyncTask execute

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

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

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

    @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對象盛险,也就是傳進(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對象苦掘,這個(gè)AsyncTaskResult對象是什么呢?

   @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對象(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)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市鸡挠,隨后出現(xiàn)的幾起案子辉饱,更是在濱河造成了極大的恐慌,老刑警劉巖拣展,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件彭沼,死亡現(xiàn)場離奇詭異,居然都是意外死亡备埃,警方通過查閱死者的電腦和手機(jī)姓惑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來按脚,“玉大人于毙,你說我怎么就攤上這事「ò幔” “怎么了唯沮?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長堪遂。 經(jīng)常有香客問我介蛉,道長,這世上最難降的妖魔是什么溶褪? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任币旧,我火速辦了婚禮,結(jié)果婚禮上猿妈,老公的妹妹穿的比我還像新娘吹菱。我一直安慰自己,他們只是感情好彭则,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布鳍刷。 她就那樣靜靜地躺著,像睡著了一般俯抖。 火紅的嫁衣襯著肌膚如雪输瓜。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機(jī)與錄音前痘,去河邊找鬼。 笑死担忧,一個(gè)胖子當(dāng)著我的面吹牛芹缔,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播瓶盛,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼最欠,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了惩猫?” 一聲冷哼從身側(cè)響起芝硬,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎轧房,沒想到半個(gè)月后拌阴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡奶镶,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年迟赃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片厂镇。...
    茶點(diǎn)故事閱讀 39,926評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡纤壁,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出捺信,到底是詐尸還是另有隱情酌媒,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布迄靠,位于F島的核電站秒咨,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏梨水。R本人自食惡果不足惜拭荤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望疫诽。 院中可真熱鬧舅世,春花似錦、人聲如沸奇徒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽摩钙。三九已至罢低,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背网持。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工宜岛, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人功舀。 一個(gè)月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓萍倡,卻偏偏與公主長得像,于是被迫代替她去往敵國和親辟汰。 傳聞我的和親對象是個(gè)殘疾皇子列敲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評論 2 354

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