AsyncTask中的几个方法才能完成对任务的定制。经常需要去重写的方法有以下四个:
- 1.onPreExecute()
这个方法会在后台任务开始执行之间调用,用于进行一些界面上的初始化操作,比如显示一个进度条对话框等。
- 2.doInBackground(Params...)
这个方法中的所有代码都会在子线程中运行,我们应该在这里去处理所有的耗时任务。任务一旦完成就可以通过return语句来将任务的执行结果进行返回,如果AsyncTask的第三个泛型参数指定的是Void,就可以不返回任务执行结果。注意,在这个方法中是不可以进行UI操作的,如果需要更新UI元素,比如说反馈当前任务的执行进度,可以调用publishProgress(Progress...)方法来完成。
- 3.onProgressUpdate(Progress...)
当在后台任务中调用了publishProgress(Progress...)方法后,这个方法就很快会被调用,方法中携带的参数就是在后台任务中传递过来的。在这个方法中可以对UI进行操作,利用参数中的数值就可以对界面元素进行相应的更新。
- 4.onPostExecute(Result)
当后台任务执行完毕并通过return语句进行返回时,这个方法就很快会被调用。返回的数据会作为参数传递到此方法中,可以利用返回的数据来进行一些UI操作,比如说提醒任务执行的结果,以及关闭掉进度条对话框等。
重写之后我们需要new AsyncTask的子类,然后通常会调用以下的方法执行任务:
- 1.sub.execute(Param...)
- 2.sub.executeOnExecutor(ThreadPoolExecutor exec,Param...)
现在我们来看看在源码中,这几个方法时怎么样被调用的。首先从AsyncTask的构造函数说起
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
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 occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
在构造方法中,主要是初始化了mWork和mFuture两个变量,mWork是一个callable对象,mFuture是一个FutureTask对象,在初始化过程中将mWrok传到了mFuture当中,稍后会用到这两个对象。接下来的逻辑是执行execute(Param..)或者executeOnExecutor(X)方法,我们先看看execute方法
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
execute只是帮我们封装了executeOnExecutor方法,有一个默认的executor线程池。接下来看看executeExecutor方法
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;
}
在executeExecutor方法中,有两个关键点,mStatues默认是Status.PENDING,接下来执行了我们重写的onPreExecute()方法,该方法是在UI线程执行的,所以一般是进行界面的初始化操作,eg:显示进度条。往下走将mFuture作为参数执行了exec的execute方法,exec就是上面sDefualtExecutor。
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
sDefualtExecutor其实就是一个静态的SerialExecutor常量,接下来将执行SerialExecutor的execute方法
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);
}
}
}
SerialExecutor使用ArrayDeque队列来管理我们的Runnable对象,SerialExecutor线程执行往ArrayDeque队尾插入Runnable对象,也就是mFuture,以及从队头取出Runnable对象传递给THEAD_POOL_EXECUTOR线程池执行。
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
THEAD_POOL_EXECUTOR是一个静态的线程池常量,负责执行Runnable对象(mFuture)。往下走,从THEAD_POOL_EXECUTOR线程池其中一个工作线程将执行Runnable对象。也就是mFuture.run()。
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
在这个方法中,主要是执行了c.call()。c对象初始化mFurture的时候传入的mWrok,往下看,接下来执行mWrok.call()。(在THEAD_POOL_EXECUTOR线程池的一个工作线程中执行)往下看mWrok.call()。
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
看到了doInBackground方法了。因为该方法在子线程子线程中执行,因此doInBackground去处理所有的耗时任务。往下看
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
doInBackground返回的Result变量将通过Message对象封装被子线程发送给UI线程的Handler对象sHandler,handleMessge方法处理。
private static final InternalHandler sHandler = new InternalHandler();
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,调用了AsyncTask的finish方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
UI线程判断该任务是否取消,若没有取消,则执行我们重写的onPostExecute方法。可以利用返回的数据来进行一些UI操作,比如说提醒任务执行的结果,以及关闭掉进度条对话框等。回头看看Message_POST_PROGRESS字段,没错,该字段执行了我们重写的onProgressUpdate方法,用于在doInBackground()过程中更新进度条等。没猜错的话是在doInBackground()调用publishiProgeress(),该方法发送给sHandler。看源码
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
果然是在这里发送给sHandler的。
至此分析完了AsyncTask.execute的执行过程。
总结
通过上面的分析,我们知道AsyncTask.execute的执行过程,SerialExecutor是在THREAD_POOL_EXECUTOR的基础上添加一个mTasks的队列来保证任务的顺序执行。至于executeOnExecutor(ThreadPoolExecutor exec,Param...)允许开发者自定义线程池来运行和调度Thread,此时就没有了SerialExecutor来保证任务的顺序执行