AsyncTask解析

1.基本原理

AsyncTask的基本原理是:線程池 + Handler,內(nèi)部封裝了2個(gè)線程池和1個(gè)Handler;線程池負(fù)責(zé)線程調(diào)度和執(zhí)行任務(wù),Handler負(fù)責(zé)異步通信。

成員變量 具體作用
THREAD_POOL_EXECUTOR(線程池) 執(zhí)行任務(wù)的線程
sBackupExecutor(線程池) 使用隊(duì)列,配合任務(wù)調(diào)度
mHandler 工作線程與主線程之間的通信

主要回調(diào)方法

  • onPreExecute()
  • doInBackground(Params... params)
  • onProgressUpdate(Progress... values)
  • onPostExecute(Result result)
  • onCancelled(Result result)

這是整個(gè)流程中關(guān)鍵節(jié)點(diǎn)的方法,在調(diào)用execute()方法之后,按照順序onPreExecute() -> doInBackground(Params... params) -> onPostExecute(Result result).

如果調(diào)用cancel方法取消的當(dāng)前任務(wù),最后會(huì)執(zhí)行onCancelled(Result result)替代onPostExecute

doInBackground方法中還可以可以調(diào)用onProgressUpdate(Progress... values)方法更新任務(wù)進(jìn)度。

2.分析

AsyncTask構(gòu)造器

AsyncTask的構(gòu)造器分別創(chuàng)建了Handler,WorkerRunnableFutureTask一個(gè)對(duì)象。

源碼中的的構(gòu)造器,有三個(gè),但是實(shí)際能使用的只有AsyncTask(),后兩個(gè)都被hide了無法調(diào)用,這一點(diǎn)就限制了Handler在創(chuàng)建的時(shí)候,一定是在UI線程的。

  • AsyncTask()
  • AsyncTask(Handler handler)
  • AsyncTask(Looper callbackLooper)

這個(gè)內(nèi)部默認(rèn)的Handler實(shí)現(xiàn)代碼如下:

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

        @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ā)送結(jié)果和更新progress事件。

WorkerRunnable其實(shí)是用來暫存Params[]Callable接口,Callable接口只有call()

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

在創(chuàng)建WorkerRunnable對(duì)象時(shí),實(shí)現(xiàn)了call()方法

mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
        //1.修改Task是否執(zhí)行為true
        mTaskInvoked.set(true);
        Result result = null;
        try {
            //2.設(shè)置線程優(yōu)先級(jí)
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //3.執(zhí)行doInBackground方法,獲取結(jié)果
            result = doInBackground(mParams);
            Binder.flushPendingCommands();
        } catch (Throwable tr) {
            //4.發(fā)生異常,修改是否取消狀態(tài)為true
            mCancelled.set(true);
            throw tr;
        } finally {
            //5.同過mHandler發(fā)送result
            postResult(result);
        }
        return result;
    }
};

創(chuàng)建了1個(gè)FutureTask類的對(duì)象,復(fù)寫了done(),這里注意FutureTask在創(chuàng)建的時(shí)候傳入WorkerRunnable的示例對(duì)象,在FutureTask的run方法中會(huì)執(zhí)行WorkerRunnable的call方法

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

//-------------- 分割線 --------------
private void postResultIfNotInvoked(Result result) {
    //獲取task執(zhí)行的標(biāo)記,沒有執(zhí)行則通過mHandler發(fā)送結(jié)果
    final boolean wasTaskInvoked = mTaskInvoked.get();
    if (!wasTaskInvoked) {
        postResult(result);
    }
}

FutureTask是實(shí)現(xiàn)了Runnable和Future接口的類,主要是維護(hù)了Task在整個(gè)過程中的一個(gè)狀態(tài),在execute()方法中最終執(zhí)行的就是FutureTask的示例對(duì)象。

execute()

execute其實(shí)是調(diào)用了executeOnExecutor方法,將task加入到任務(wù)隊(duì)列的線程池中,然后按順序執(zhí)行

對(duì)于mStatus這個(gè)狀態(tài)可以看到,每個(gè)AsyncTask只能執(zhí)行一次,執(zhí)行中或者已經(jīng)完成的AsyncTask在此執(zhí)行都會(huì)拋出IllegalStateException

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

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

總結(jié)

AsyncTask就是對(duì)了耗時(shí)操作時(shí)的線程調(diào)度和任務(wù)狀態(tài)管理,雖然現(xiàn)在基本不使用,但是部分的代碼寫法還是值得學(xué)習(xí)的。

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

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