AsyncTask源码解析

本文主要围绕AsyncTask的源码对其进行原理分析,帮助理解AsyncTask工作流程以及更好的运用, 若发现错误的地方望告知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
new AsyncTask<String, String, String>() {

// 2. 运行在主线程中, 初始准备操作.
public void onPreExecute() {

}

// 3. 运行在子线程中, 通常做一些耗时的任务.
public String doInBackground(String... params) {
return null;
}

// 4. 运行主线程中, result就是doInBackground方法返回的值. 即本次任务完成时执行.
public void onPostExecute(String result) {

}
// 任务进度更新 运行在主线程
protected void onProgressUpdate(String... values) {

}

// 任务被取消时执行 运行在主线程
protected void onCancelled(String result) {

}
}.execute(String... params); // 1. 开始执行异步任务.

要想启动AsyncTask我们就必须执行execute的方法, 那我们就从这个函数开始 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
mStatus = Status.RUNNING;

// 这里在创建AsyncTask的构造对象里调用了onPreExecute 运行在当前线程中.
onPreExecute();

// 把mWorker中的mParams赋值为用户传递进来的参数.
mWorker.mParams = params;

// sExecutor使用线程池, 执行任务. 这时进入到子线程中.
// AsyncTask构造函数在一开始使用异步任务时, 已经调用.
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
}
};

// 1. 把mWorker对象传递给了FutureTask的构造函数
mFuture = new FutureTask<Result>(mWorker) {

@Override
protected void done() {

}
};
}
sExecutor.execute(mFuture);
return this;
}

// AsyncTask构造函数在一开始使用异步任务时, 已经调用.
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
...
}
};

// 1. 把mWorker对象传递给了FutureTask的构造函数
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
...
}
};
}

FutureTask类中接收的是Callable的类型, 其实WorkerRunnable类型实现了Callable的类型. 代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public FutureTask(Callable<V> callable) {  
if (callable == null)
throw new NullPointerException();
// 2. 把callable(mWorker)传递给了Sync的构造函数.
sync = new Sync(callable);
}

Sync(Callable<V> callable) {
// 3. 把接收过来的callable(mWorker)对象赋值给Sync类中的成员变量callable
// 总结: Sync类中的成员变量callable就是AsyncTask中的mWorker对象.
this.callable = callable;
}

mFuture对象中的run方法如下:
public void run() {
// 1. 调用了innerRun方法.
sync.innerRun();
}

void innerRun() {
if (!compareAndSetState(READY, RUNNING))
return;

runner = Thread.currentThread();
if (getState() == RUNNING) { // recheck after setting thread
V result;
try {
// 2. 调用了callable(mWorker)的call方法. 获取一个返回结果.
result = callable.call();
} catch (Throwable ex) {
setException(ex);
return;
}
// 4. 把结果传递给set方法.
set(result);
} else {
releaseShared(0); // cancel
}
}

在AsyncTask的构造函数中, mWorker对象初始化时, 已经覆盖了call方法, 代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}


private Result postResult(Result result) {
@SuppressWarnings("unchecked") // 拿到已经创建的Handle
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget(); // 发送到MessageQueue
return result;
}

// 创建的handle
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}

最后我们来看看在handler里的逻辑处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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); // 这里的函数也是经常用到通常更新ui进度
break;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}


private void finish(Result result) {
if (isCancelled()) {
onCancelled(result); // 这里执行取消操作
} else {
onPostExecute(result);
// 14. 把doInBackground的返回结果传递给用户实现的onPostExecute方法. 运行在主线程中, 用户可以做一些操作界面, 更新界面的操作.
}
mStatus = Status.FINISHED;
}