AsyncTask
- onPreExecute(),在主线程中执行,在异步任务之前该方法会被执行,可以用来做一些准备工作
- doInBackground(),在线程池中执行,用于执行异步任务,在此方法中可以通过调用publishProgress方法更新任务的进度,publishProgres方法中会调用onProgressUpdate方法,另外doInBackground()需要返回计算结果给onPostExecute()方法
- onProgressUpdate(),在主线程中执行,当后台任务的执行进度发生改变时此方法会调用
- onPostExecute(),在主线程中执行,在异步任务执行之后,此方法会被调用
使用注意事项:
- AsyncTask的对象必须在主线程中创建
- execute方法必须在UI线程中调用
- 一个AsyncTask对象只能执行一次,即只能执行一次execute方法
- 不要再程序中直接调用onPreExecute、doInBackground、onProgressUpdate、onPostExecute方法
- Android1.6之前是串行执行任务,1.6之后采用线程池并行执行任务,3.0后为了避免并发错误又采用一个线程串行执行任务
工作原理:
AsyncTask内部封装了线程池和Handler,方便在子线程中更新ui。AsyncTask内部有两个线程池(SerialExecutor和THREAD_POOL_EXECUTOR)和一个handler,其中SerialExecutor用于任务排队,THREAD_POOL_EXECUTOR用于真正执行任务,handler将执行环境切换至主线程
为了分析AsyncTask工作原理,我们从他的execute()方法开始分析,execute()方法会调用executeOnExecutor方法,实现如下:
@MainThread//主线程中执行
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
executeOnExecutor()方法:
@MainThread
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;
}
在上述代码中,sDefaultExecutor其实是一个串行的线程池,一个进程中的所有AsyncTask任务都会在这个线程池中排队,在executeOnExecutor()方法中,会先执行onPreExecute()
方法,然后开始执行线程池,下面分析一下sDefaultExecutor线程池的实现
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);
}
}
}
从上述代码可以看出AsyncTask的排队执行过程,execute(final Runnable r)
方法会将runnable对象插入到mTasks队列当中,这里的runnable对象就是,通过params参数封装成的FutureTask对象,如果这个时候没有正在活动的任务,那么就会调用scheduleNext()
方法来执行下一个任务,同时,当这个任务执行完毕后,会自动的调用scheduleNext()
方法来执行下一个任务,由此可以看出,AsyncTask是串行执行的,在scheduleNext()
犯法中真正执行任务的是THREAD_POOL_EXECUTOR
线程池,前面说过执行的runnable对象是futureTask,我们看一下futureTask的run方法:
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, 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);
}
}
在run方法中代码执行的是result = c.call();
语句,而这个callback也就是在asyncTask中初始化futureTask对象传入的WorkerRunnable对象,我们接着看一下WorkerRunnable对象的实现:
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;
}
};
我们看到,mWorker.call()
方法首先会设置mTaskInvoked.set(true);
表示当前任务已经执行过了,然后会执行doInBackground
方法,接着将返回值传递给postResult
方法,postResult
方法实现如下:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
可以看到,在postResult
方法中会通过handler将result结果发送给主线程,之后会在祝线程中调用onPostExecute()方法