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