編輯:關於 Android 開發
AsyncTask 天天在用,但它內部的原理一直沒有特意研究。今天趁著有時間,把它的運行機制記錄下來。
具體用法就不再贅述,先寫一個最基本的子類:
class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... voids) {
return true;
}
}
啟動方式大家也都知道:
new MyAsyncTask().execute("參數");
平時寫到這裡我們就不再深究了,因為任務已經跑起來。但仔細想想,有幾個問題值得追問:
execute() 就能運行?doInBackground() 裡不能操作 UI,而 onPostExecute() 就可以?接下來就一步一步看它內部到底做了哪些事。
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(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);
}
}
};
}
看著程式碼不少,其實就是 new 了兩個物件:mWorker 與 mFuture,它們分別是 Callable 與 Future 的實作。值得注意的是,在實例化 mFuture 時,把 mWorker 當作參數傳了進去——這是兩者能串起來的關鍵。
@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;
}
幾個重點:
狀態檢查。 這也解釋了為什麼一個 AsyncTask 只能執行一次——執行完狀態變成 FINISHED,再呼叫就會拋出 IllegalStateException。
onPreExecute() 先跑。 這證明它確實早於 doInBackground,適合做一些前置準備工作。
參數被塞進 mWorker。 然後第 26 行呼叫 Executor 的 execute(),並把 mFuture 當作參數傳入。
那個 exec 是從哪來的?看 sDefaultExecutor 的定義:
public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
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);
}
}
}
傳入的 Runnable 其實就是我們的 mFuture(FutureTask 同時實作了 Future 與 Runnable)。execute() 會先把 mFuture 放進 mTasks,此時 mActive 還是 null,於是呼叫 scheduleNext(),從佇列取出第一個丟進線程池開始執行。
這裡有個關鍵設計:SerialExecutor 用一個 mActive 作為「 Currently 執行中」的標記,只有當前一任務跑完、在 finally 中呼叫 scheduleNext 時,才會取下一個。因此預設情況下多個 AsyncTask 是排隊串行執行的,而非並行。
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(result);
}
第 4 行把執行緒優先級調低為背景等級,第 6 行就是我們熟悉的 doInBackground()。重點來了:這段程式碼跑在另一條執行緒上,這正是為什麼在 doInBackground 裡不能操作 UI。最後把結果交給 postResult()。
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
這裡就是我們熟悉的 Handler 了。它的實作如下:
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper()); // 綁定主執行緒的 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;
}
}
}
Looper.getMainLooper() 就是答案所在——Handler 綁在主執行緒上,所以 handleMessage 自然在主執行緒執行。
由於我們發送的是 MESSAGE_POST_RESULT,會走到第 13 行的 finish():
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
一目了然:最後呼叫了我們的 onPostExecute(),並把結果傳過去,同時把狀態標記為 FINISHED。整個流程就是這樣。
仔細看會發現,mFuture 實例化時覆寫的 done() 到目前都沒派上用場,它在整個流程中扮演什麼角色?
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);
}
}
從命名應該能猜到,這個方法在整個非同步任務執行完之後被呼叫。在 Future 中,透過 get() 就能取得 mWorker 中 call 方法的回傳值。接著看 postResultIfNotInvoked:
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
你可能會問:postResult() 怎麼被呼叫了兩次?看方法名就明白了——「post result if not invoked」,這次的呼叫是保險機制,防止 call() 因故沒執行到 postResult 時結果遺失。
開關就是 mTaskInvoked,它是個 AtomicBoolean。在 call 方法開頭我們看過:
mTaskInvoked.set(true);
所以正常流程下,執行過 call 之後這裡會讀到 true,後續就不會重複執行,從而保證 postResult 只被呼叫一次。
整條鏈路串起來是:execute → SerialExecutor 排隊 → 線程池執行 mFuture → mWorker.call → doInBackground(背景執行緒)→ postResult → InternalHandler(主執行緒)→ onPostExecute。
理解這條鏈路有幾個實用價值:知道預設是串行的,就明白為什麼多個下載任務會互相等待,此時應改用 executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ...);知道 Handler 綁在主 Looper,就明白為什麼 onProgressUpdate 能安全更新 UI;也知道它為何只能執行一次。
Android 登入客戶端實戰:驗證碼抓取、網頁資料解析與 HttpWatch 抓包入門
在行動網路無所不在的今天,一個不連網的 App 很難有長遠生命週期,因此網路程式設計是每個 Android 開發者的必修課。這篇以「模擬登入學校教務系統」為案例,完整走一
Android 設計模式入門:從原始碼理解常見設計模式
為什麼要在 Android 中談設計模式設計模式並不是為了背誦而存在,而是為了更有效率的解決常見問題。閱讀 Android 原始碼時,會發現許多熟悉的元件其實都使用了典型
Android Studio 如何匯入 jar 套件:告別 Eclipse 思維的簡便做法
在 Android Studio 中加入外部 jar 的輕鬆流程 Android Studio 在開發 Android APK 時確實十分便利,但它的許多設定都與老搭檔
XUtils 踩坑記錄:Android 6.0 移除 HttpClient 與模擬器 IP 之謎
使用 XUtils 框架時遇到的兩個問題 問題一:Android 6.0 找不到 Apache HttpClient 接入 XUtils 後,程式一跑就拋出 NoCla