Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android AsyncTask 使用步驟與源碼逐行解析

編輯:關於 Android 程式設計

AsyncTask 最典型的應用場景是「後台下載文件並實時更新進度」:它既能讓耗時操作在後台線程執行,又能與主線程通信以更新 UI;同時內部使用線程池,能處理多任務請求。

但它有一個讓很多人困惑的行為:同一個 AsyncTask 實例只能執行一次。為什麼明明有線程池卻不能反覆提交任務?答案要從源碼裡找。

一、使用步驟

1. 子類化 AsyncTask

2. 實現以下一個或多個方法

  • onPreExecute():在後台操作執行前由 UI 線程調用,適合做初始化,例如顯示進度條。
  • doInBackground(Params...):在 onPreExecute 之後立即執行,運行於後台線程,負責耗時計算。可調用 publishProgress 更新進度。這是唯一的抽象方法,子類必須實現。
  • onProgressUpdate(Progress...):publishProgress 被調用後,由 UI 線程回調,用於在界面上展示進展。
  • onPostExecute(Result):doInBackground 執行完畢後由 UI 線程調用,把後台計算結果交給 UI 線程。

3. 提交任務

使用 execute() 或 executeOnExecutor()。同時注意四條規則:

  • Task 實例必須在 UI 線程中創建;
  • execute 方法必須在 UI 線程中調用;
  • 不要手動調用那四個回調方法,它們由系統調用;
  • 該 task 只能被執行一次,重複調用會拋異常。

二、困惑的起點

既然內部有線程池,直覺上應該可以這樣寫:

AsyncTask asyncTask = new XXAsyncTask();
asyncTask.execute(1);
asyncTask.execute(2);
asyncTask.execute(3);

結果程序立刻崩潰。那正確姿勢是什麼?比如要提交 10 個任務:

for (int i = 0; i < 10; i++) {
    AsyncTask asyncTask = new XXAsyncTask();   // 每次都 new 一個
    asyncTask.execute(i);
}

難道不是每個 AsyncTask 各有一個線程池嗎?還真不是。

三、線程池其實是靜態共享的

/** 可以並行執行任務的線程池 */
public static final Executor THREAD_POOL_EXECUTOR =
        new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

/** 串行執行任務的線程池 */
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

兩個線程池都是 static final,因此整個進程中的所有 AsyncTask 實例共享這兩個線程池。默認使用 SERIAL_EXECUTOR(串行),若需要並行可通過 executeOnExecutor 指定:

asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 1);

四、execute 的入口

@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    return executeOnExecutor(sDefaultExecutor, params);
}
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

默認線程池正是 SERIAL_EXECUTOR。接著看 executeOnExecutor:

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

答案在這裡揭曉。Status 只有三個值:

public enum Status {
    PENDING,   // 尚未執行
    RUNNING,   // 正在執行
    FINISHED,  // onPostExecute 已結束
}

第一次調用 execute 時,狀態由 PENDING 變為 RUNNING;第二次調用時狀態仍是 RUNNING,於是拋出 IllegalStateException。這就是為什麼必須每次 new 一個新實例——不是線程池的限制,而是狀態機的限制。

五、Step 1:onPreExecute

接著調用 onPreExecute()。此方法運行在 UI 線程,可以安全地更新界面、做初始化工作,此時後台任務尚未開始。

六、Step 2:SerialExecutor 的串行機制

exec.execute(mFuture);

SERIAL_EXECUTOR 的實現很精巧:

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

private static class SerialExecutor implements Executor {
    final ArrayDeque<Runnable> mTasks = new ArrayDeque<>();
    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);
        }
    }
}

邏輯是:新任務先入隊 mTasks;若當前沒有活躍任務(mActive 為 null),調用 scheduleNext 從隊首取出並提交給真正的線程池 THREAD_POOL_EXECUTOR。每個任務執行完畢後在 finally 中調用 scheduleNext 觸發下一個——串行由此保證。

七、Step 3:mFuture 與 mWorker

被提交的是 mFuture,它的定義如下:

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

它是一個 FutureTask,構造時傳入了 mWorker:

mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
        mTaskInvoked.set(true);
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        Result result = doInBackground(mParams);   // 我們的後台邏輯在這裡執行
        Binder.flushPendingCommands();
        return postResult(result);
    }
};

可見 mWorker 是一個 Callable,而 mFuture 本質上是 Runnable。FutureTask 構造時把 callable 保存下來:

public FutureTask(Callable<V> callable) {
    if (callable == null) throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;
}

八、Step 4:FutureTask.run 與 doInBackground

public void run() {
    if (state != NEW || !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread())) return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();      // 調用 mWorker.call(),內部執行 doInBackground
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran) set(result);
        }
    } finally {
        runner = null;
        int s = state;
        if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s);
    }
}

至此可以回答最初的三個問題:

  1. doInBackground 在哪個線程執行? 它在 mWorker.call() 中被調用,而 mWorker.call() 由 mFuture.run() 觸發,mFuture 又是被 THREAD_POOL_EXECUTOR 提交執行的——所以運行在後台線程池中。
  2. 線程優先級如何? call() 開頭就把線程優先級設為 THREAD_PRIORITY_BACKGROUND,避免後台任務搶佔 UI 資源。
  3. 結果如何回到主線程? 由 call() 末尾的 postResult 完成。

九、Step 5:postResult 與 InternalHandler

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

InternalHandler 的構造函數決定了它綁定的是主線程 Looper:

public InternalHandler() {
    super(Looper.getMainLooper());
}
public void handleMessage(Message msg) {
    AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
    switch (msg.what) {
        case MESSAGE_POST_RESULT:
            result.mTask.finish(result.mData[0]);
            break;
        case MESSAGE_POST_PROGRESS:
            result.mTask.onProgressUpdate(result.mData);
            break;
    }
}
private void finish(Result result) {
    if (isCancelled()) {
        onCancelled(result);
    } else {
        onPostExecute(result);
    }
    mStatus = Status.FINISHED;
}

消息一到主線程,就調用 finish,進而回調 onPostExecute,並把狀態置為 FINISHED——這也解釋了為什麼第二個任務連「正在運行」都算不上就直接報「已執行過」。

十、onProgressUpdate 是怎麼被調用的

只剩下它了。 ourselves 需要主動調用 publishProgress:

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

它同樣是發消息,只是 what 為 MESSAGE_POST_PROGRESS,因此在 handleMessage 中走的是 result.mTask.onProgressUpdate(result.mData) 分支。至此四個回調的調用路徑全部打通。

小結

  • 兩個線程池是靜態的,全部實例共享;默認串行,可切換為並行。
  • 一個實例只能執行一次,這是 Status 狀態機的設計,與線程池無關。
  • doInBackground 在後台線程池執行,其餘三個回調都在主線程,切換靠 FutureTask + Handler 組合完成。
  • 註:AsyncTask 在 Android 11(API 30)中已被標記為不推薦使用,新項目建議改用 Kotlin 協程、WorkManager 或 RxJava 等方案,理解其原理有助於遷移與維護舊代碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved