-
protected Boolean doInBackground(Void… params) {
-
try {
-
while (true) {
-
int downloadPercent = doDownload();
-
publishProgress(downloadPercent);
-
if (downloadPercent >= 100) {
-
break;
-
}
-
}
-
} catch (Exception e) {
-
return false;
-
}
-
return true;
-
}
-
@Override
-
protected void onProgressUpdate(Integer… values) {
-
progressDialog.setMessage(“当前下载进度:” + values[0] + “%”);
-
}
-
@Override
-
protected void onPostExecute(Boolean result) {
-
progressDialog.dismiss();
-
if (result) {
-
Toast.makeText(context, “下载成功”, Toast.LENGTH_SHORT).show();
-
} else {
-
Toast.makeText(context, “下载失败”, Toast.LENGTH_SHORT).show();
-
}
-
}
-
}
这里我们模拟了一个下载任务,在doInBackground()方法中去执行具体的下载逻辑,在onProgressUpdate()方法中显示当前的下载进度,在onPostExecute()方法中来提示任务的执行结果。如果想要启动这个任务,只需要简单地调用以下代码即可:
[java] view plain copy
- new DownloadTask().execute();
以上就是AsyncTask的基本用法,怎么样,是不是感觉在子线程和UI线程之间进行切换变得灵活了很多?我们并不需求去考虑什么异步消息处理机制,也不需要专门使用一个Handler来发送和接收消息,只需要调用一下publishProgress()方法就可以轻松地从子线程切换到UI线程了。
虽然AsyncTask这么简单好用,但你知道它是怎样实现的吗?那么接下来,我们就来分析一下AsyncTask的源码,对它的实现原理一探究竟。注意这里我选用的是Android 4.0的源码,如果你查看的是其它版本的源码,可能会有一些出入。
从之前DownloadTask的代码就可以看出,在启动某一个任务之前,要先new出它的实例,因此,我们就先来看一看AsyncTask构造函数中的源码,如下所示:
[java] view plain copy
-
public AsyncTask() {
-
mWorker = new WorkerRunnable<Params, Result>() {
-
public Result call() throws Exception {
-
mTaskInvoked.set(true);
-
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
-
return postResult(doInBackground(mParams));
-
}
-
};
-
mFuture = new FutureTask(mWorker) {
-
@Override
-
protected void done() {
-
try {
-
final Result result = get();
-
postResultIfNotInvoked(result);
-
} 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) {
-
postResultIfNotInvoked(null);
-
} catch (Throwable t) {
-
throw new RuntimeException("An error occured while executing "
-
+ “doInBackground()”, t);
-
}
-
}
-
};
-
}
这段代码虽然看起来有点长,但实际上并没有任何具体的逻辑会得到执行,只是初始化了两个变量,mWorker和mFuture,并在初始化mFuture的时候将mWorker作为参数传入。mWorker是一个Callable对象,mFuture是一个FutureTask对象,这两个变量会暂时保存在内存中,稍后才会用到它们。
接着如果想要启动某一个任务,就需要调用该任务的execute()方法,因此现在我们来看一看execute()方法的源码,如下所示:
[java] view plain copy
-
public final AsyncTask<Params, Progress, Result> execute(Params… params) {
-
return executeOnExecutor(sDefaultExecutor, params);
-
}
简单的有点过分了,只有一行代码,仅是调用了executeOnExecutor()方法,那么具体的逻辑就应该写在这个方法里了,快跟进去瞧一瞧:
[java] view plain copy
-
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;
-
}
果然,这里的代码看上去才正常点。可以看到,在第15行调用了onPreExecute()方法,因此证明了onPreExecute()方法会第一个得到执行。可是接下来的代码就看不明白了,怎么没见到哪里有调用doInBackground()方法呢?别着急,慢慢找总会找到的,我们看到,在第17行调用了Executor的execute()方法,并将前面初始化的mFuture对象传了进去,那么这个Executor对象又是什么呢?查看上面的execute()方法,原来是传入了一个sDefaultExecutor变量,接着找一下这个sDefaultExecutor变量是在哪里定义的,源码如下所示:
[java] view plain copy
-
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
-
……
-
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
可以看到,这里先new出了一个SERIAL_EXECUTOR常量,然后将sDefaultExecutor的值赋值为这个常量,也就是说明,刚才在executeOnExecutor()方法中调用的execute()方法,其实也就是调用的SerialExecutor类中的execute()方法。那么我们自然要去看看SerialExecutor的源码了,如下所示:
[java] view plain copy
-
private static class SerialExecutor implements Executor {
-
final ArrayDeque mTasks = new ArrayDeque();
-
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);
-
}
-
}
-
}
SerialExecutor类中也有一个execute()方法,这个方法里的所有逻辑就是在子线程中执行的了,注意这个方法有一个Runnable参数,那么目前这个参数的值是什么呢?当然就是mFuture对象了,也就是说在第9行我们要调用的是FutureTask类的run()方法,而在这个方法里又会去调用Sync内部类的innerRun()方法,因此我们直接来看innerRun()方法的源码:
[java] view plain copy
-
void innerRun() {
-
if (!compareAndSetState(READY, RUNNING))
-
return;
-
runner = Thread.currentThread();
-
if (getState() == RUNNING) { // recheck after setting thread
-
V result;
-
try {
-
result = callable.call();
-
} catch (Throwable ex) {
-
setException(ex);
-
return;
-
}
-
set(result);
-
} else {
-
releaseShared(0); // cancel
-
}
-
}
可以看到,在第8行调用了callable的call()方法,那么这个callable对象是什么呢?其实就是在初始化mFuture对象时传入的mWorker对象了,此时调用的call()方法,也就是一开始在AsyncTask的构造函数中指定的,我们把它单独拿出来看一下,代码如下所示:
[java] view plain copy
-
public Result call() throws Exception {
-
mTaskInvoked.set(true);
-
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
-
return postResult(doInBackground(mParams));
-
}
在postResult()方法的参数里面,我们终于找到了doInBackground()方法的调用处,虽然经过了很多周转,但目前的代码仍然是运行在子线程当中的,所以这也就是为什么我们可以在doInBackground()方法中去处理耗时的逻辑。接着将doInBackground()方法返回的结果传递给了postResult()方法,这个方法的源码如下所示:
[java] view plain copy
-
private Result postResult(Result result) {
-
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
-
new AsyncTaskResult(this, result));
-
message.sendToTarget();
-
return result;
-
}
如果你已经熟悉了异步消息处理机制,这段代码对你来说一定非常简单吧。这里使用sHandler对象发出了一条消息,消息中携带了MESSAGE_POST_RESULT常量和一个表示任务执行结果的AsyncTaskResult对象。这个sHandler对象是InternalHandler类的一个实例,那么稍后这条消息肯定会在InternalHandler的handleMessage()方法中被处理。InternalHandler的源码如下所示:
[java] view plain copy
-
private static class InternalHandler extends Handler {
-
@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;
-
}
-
}
-
}
这里对消息的类型进行了判断,如果这是一条MESSAGE_POST_RESULT消息,就会去执行finish()方法,如果这是一条MESSAGE_POST_PROGRESS消息,就会去执行onProgressUpdate()方法。那么finish()方法的源码如下所示:
[java] view plain copy
-
private void finish(Result result) {
-
if (isCancelled()) {
-
onCancelled(result);
-
} else {
-
onPostExecute(result);
-
}
-
mStatus = Status.FINISHED;
-
}
可以看到,如果当前任务被取消掉了,就会调用onCancelled()方法,如果没有被取消,则调用onPostExecute()方法,这样当前任务的执行就全部结束了。
我们注意到,在刚才InternalHandler的handleMessage()方法里,还有一种MESSAGE_POST_PROGRESS的消息类型,这种消息是用于当前进度的,调用的正是onProgressUpdate()方法,那么什么时候才会发出这样一条消息呢?相信你已经猜到了,查看publishProgress()方法的源码,如下所示:
[java] view plain copy
-
protected final void publishProgress(Progress… values) {
-
if (!isCancelled()) {
-
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
-
new AsyncTaskResult(this, values)).sendToTarget();
-
}
-
}
非常清晰了吧!正因如此,在doInBackground()方法中调用publishProgress()方法才可以从子线程切换到UI线程,从而完成对UI元素的更新操作。其实也没有什么神秘的,因为说到底,AsyncTask也是使用的异步消息处理机制,只是做了非常好的封装而已。
读到这里,相信你对AsyncTask中的每个回调方法的作用、原理、以及何时会被调用都已经搞明白了吧。
不得不说,刚才我们在分析SerialExecutor的时候,其实并没有分析的很仔细,仅仅只是关注了它会调用mFuture中的run()方法,但是至于什么时候会调用我们并没有进一步地研究。其实SerialExecutor也是AsyncTask在3.0版本以后做了最主要的修改的地方,它在AsyncTask中是以常量的形式被使用的,因此在整个应用程序中的所有AsyncTask实例都会共用同一个SerialExecutor。下面我们就来对这个类进行更加详细的分析,为了方便阅读,我把它的代码再贴出来一遍:
[java] view plain copy
-
private static class SerialExecutor implements Executor {
-
final ArrayDeque mTasks = new ArrayDeque();
-
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);
-
}
-
}
-
}
可以看到,SerialExecutor是使用ArrayDeque这个队列来管理Runnable对象的,如果我们一次性启动了很多个任务,首先在第一次运行execute()方法的时候,会调用ArrayDeque的offer()方法将传入的Runnable对象添加到队列的尾部,然后判断mActive对象是不是等于null,第一次运行当然是等于null了,于是会调用scheduleNext()方法。在这个方法中会从队列的头部取值,并赋值给mActive对象,然后调用THREAD_POOL_EXECUTOR去执行取出的取出的Runnable对象。之后如何又有新的任务被执行,同样还会调用offer()方法将传入的Runnable添加到队列的尾部,但是再去给mActive对象做非空检查的时候就会发现mActive对象已经不再是null了,于是就不会再调用scheduleNext()方法。