protected void set(V v) {
// 5. 繼續把參數傳遞給innerSet方法.
sync.innerSet(v);
}
void innerSet(V v) {
for (;;) {
int s = getState();
if (s == RAN)
return;
if (s == CANCELLED) {
// aggressively release to set runner to null,
// in case we are racing with a cancel request
// that will try to interrupt runner
releaseShared(0);
return;
}
if (compareAndSetState(s, RAN)) {
// 6. 把doInBackground返回的結果賦值給成員變量result
result = v;
releaseShared(0);
// 7. 調用FutureTask中的done方法.
done();
return;
}
}
}
// 此方法定義在AsyncTask的構造函數中, 初始化mFuture時,已經覆蓋了done方法, 代碼如下:
@Override
protected void done() {
Message message;
Result result = null;
try {
// 8. 調用FutureTask中的get方法獲取result(doInBackground返回的結果).
result = get();
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
// 11. 創建一個消息對象.
// msg.what = MESSAGE_POST_RESULT;
// msg.obj = new AsyncTaskResult<Result>(AsyncTask.this, result);
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(AsyncTask.this, result));
// 12. 把當前消息使用sHandler發送出去.
message.sendToTarget();
}
public V get() throws InterruptedException, ExecutionException {
// 9. 轉調innerGet方法.
return sync.innerGet();
}
V innerGet() throws InterruptedException, ExecutionException {
...
// 10. 把result(doInBackground的結果)返回回去. result成員變量是在innerSet方法中賦值. 詳情看第6步.
return result;
}
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
// 把obj轉換成AsyncTaskResult類, 這個類中mTask對象就是當前的AsyncTask對象. mData對象就是doInBackground的返回結果.
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
// 13. 調用AsyncTask中的finish方法, 並且把doInBackground的返回結果傳遞進去.
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}
private void finish(Result result) {
if (isCancelled()) result = null;
// 14. 把doInBackground的返回結果傳遞給用戶實現的onPostExecute方法. 運行在主線程中, 用戶可以做一些操作界面, 更新界面的操作.
onPostExecute(result);
mStatus = Status.FINISHED;
}