前言
AsyncTask是很多人接触的第一个用来完成异步任务的东西。相信大家都知道它的使用方法,今天我们来看一下他的源码,来弄明白其中的原理。
源码解析
首先先从入口开始,execute方法会转入executeOnExecutor方法。
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
//sDefaultExecutor是一个SerialExecutor对象,关于他的介绍放在了文章末尾
return executeOnExecutor(sDefaultExecutor, params);
}
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;
}
private volatile Status mStatus = Status.PENDING;
AsyncTask对象的初始状态为PENDING,之后我们会介绍到,当任务被取消,或者onPostExecute()执行完之后,状态会被设置为FINISHED。
那么我们可以得到一个对开发有用的信息:
每个AsyncTask对象只能被execute一次,第二次被执行时会抛出异常。
可以看到,我们经常要重写的onPreExecute()方法在这里被调用。之后就在线程池里执行了这个任务,那么这个mFuture是在哪初始化的呢?显然只能是在构造方法里,我们去看一下
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return 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);
}
}
};
}
这里对FutureTask做一个简单的介绍,FutureTask实现了Runnable接口,所以可以在线程池中被执行。在FutureTask的Run方法中,实际上被执行的是传入的Callable的call方法,此处也就是指mWork的call方法,然后会执行FutureTask的done方法。
经过上面的介绍我们可以直到,call和done方法都运行在线程池中,doInBackground方法在call中被执行,所以doInBackground方法可以进行一些耗时操作,如网络请求和数据库操作。
可以看到,doInBackground方法的返回值被传入了postResult方法,跟踪进来:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
这里使用了Message!看到这里我想大家就应该明白了,AsyncTask中是使用Handler来实现线程的切换的。代码中是使用obtainMessage方法来获取Message对象的,这样有什么好处呢?
obtainMessage()是从消息池中回收一个Message,这样比使用New Message()来创建Message对象更节省资源。
既然已经使用sendToTarget方法将message发送,那么我们去查看对应的handler:
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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;
}
}
}
当doInBackground方法执行完之后,进入MESSAGE_POST_RESULT对应的分支,那么MESSAGE_POST_PROGRESS呢?回想一下AsyncTask中需要在主线程中运行的代码还有什么?
相信大家已经想到了,AsyncTask中需要在主线程运行的方法有两个:
- onPostExecute(),获取数据之后进行UI操作
- onProgressUpdate(),在耗时操作的时候更新进度条
首先我们来看finish方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
如果这个任务已经被取消了,那么就不会调用onPostExecute(),否则将会调用它。最后会将该AsyncTask对象的状态设置为FINISHED。这样一套流程就走完了~ 下面我们看一看关于更新进度条的部分。
我们知道,当在doInBackground()想要更新进度条的时候,应该调用publishProgress()
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
然后我们再去看一看Handler。
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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;
}
}
}
可以看到,onProgressUpdate方法会被调用。
下面我们来介绍默认的线程池。
/**
*用来将任务排队
*/
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);
}
}
}
mTask是一个队列,相信大家也能看出来,SerialExecutor是用来将任务排队的,当某一个AsyncTask类的多个对象同时调用execute()时,任务会被顺序执行,我们写个demo测试一下。
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TestAsyncTask testAsyncTask = new TestAsyncTask();
testAsyncTask.execute();
}
});
}
private class TestAsyncTask extends AsyncTask<Object,Integer,String>{
@Override
protected String doInBackground(Object... params) {
Log.d("test","doInBackground");
try{
Thread.sleep(3000);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
Log.d("test","onPostExecute");
}
}
}
然后我连续快速地点击3下button,打印结果如下:
05-10 14:12:11.623 1871-3036/com.gustiness.secondtrain D/test: doInBackground
05-10 14:12:11.623 1871-1871/com.gustiness.secondtrain D/test: onPostExecute
05-10 14:12:14.619 1871-3036/com.gustiness.secondtrain D/test: doInBackground
05-10 14:12:14.619 1871-1871/com.gustiness.secondtrain D/test: onPostExecute
05-10 14:12:17.619 1871-3036/com.gustiness.secondtrain D/test: doInBackground
05-10 14:12:17.619 1871-1871/com.gustiness.secondtrain D/test: onPostExecute
可以发现,当第一个任务执行完之后,下一个任务才会被执行,这也就验证了我们刚才的结论。
我们稍微修改一下代码,验证文章开头出的结论:每个AsyncTask对象只能被execute一次,第二次被执行时会抛出异常。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button button = (Button) findViewById(R.id.button);
final TestAsyncTask testAsyncTask = new TestAsyncTask();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
testAsyncTask.execute();
}
});
}
连续点击两次button,程序崩溃,报错信息为:
05-10 14:18:19.495 8499-8499/com.gustiness.secondtrain E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Cannot execute task: the task is already running.
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.gustiness.secondtrain.SecondActivity$1.onClick(SecondActivity.java:25)
等AsyncTask执行完成之后再点击button,程序崩溃,报错信息为:
05-10 14:21:06.171 10645-10645/com.gustiness.secondtrain E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:578)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.gustiness.secondtrain.SecondActivity$1.onClick(SecondActivity.java:25)
验证了文章开头处的结论:每个AsyncTask对象只能被执行一次。
到这里我们也就将AsyncTask的源码分析完了,是不是觉得理解的更深入一些了呢?平时养成看源码的习惯,会成长的更快,一起加油~