当android应用启动的时候会启动一条主线程,这个主线程负责向UI组件分发事件(包括绘制事件),随意当在主线程你都会阻塞UI线程,导致事件停止分发(包括绘制事件),如果UI线程blocked的时间太长(大约超过5秒),用户就会看到ANR(application not responding)的对话框,所以当我们执行耗时任务的时候要在子线程来做(访问网络、数据库查询等等),所以主线程和子线程的通信就成为了关键,android提供了handler可以让主线程和子线程通信,其中AsyncTask是通过handler和线程池来实现的轻量化异步任务的工具。(以下所有源码来自23版本)
可以看下AsyncTask类的简化代码
public abstract class AsyncTask {
abstract Result doInBackground(Params... params);
void onPreExecute() {}
protected void onProgressUpdate(Progress... values) {}
protected void onPostExecute(Result result) {}
}
可以看到AsyncTask是个抽象类,有个唯一的抽象方法是doInBackground和三个泛型Params, Progress, Result,三个泛型分别是doInBackground,onProgressUpdate,onPostExecute方法的形参类型。实现AsyncTask一般要实现代码中的那几个方法,现在让我们看看这几个方法的用处。
- doInBackground(Params… params):
就像它的名字那样,是在子线程执行的,所以耗时任务写这里面
- onPreExecute():
在execute(Params… params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记,在主线程执行
- onProgressUpdate(Progress… values):
在调用publishProgress(Progress… values)时,此方法被执行,直接将耗时任务进度信息更新到UI组件上,在主线程执行
- onPostExecute(Result result):
当后台异步任务结束,此方法将会被调用,result为doInBackground返回的结果,在主线程执行
在实现完AsyncTask抽象类后调用execute(Params… params)方法来执行异步任务。
public final AsyncTask executeOnExecutor(Executor exec, Params... params){...}
因为调用execute方法来执行异步任务,我们先从execute方法来分析。
public enum Status {
/** * Indicates that the task has not been executed yet. */
PENDING,
/** * Indicates that the task is running. */
RUNNING,
/** * Indicates that {@link AsyncTask#onPostExecute} has finished. */
FINISHED,
}
public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask 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;
}
看到execute实际是调用了executeOnExecutor()传进去了sDefaultExecutor的默认线程池,当调用了executeOnExecutor时,mStatus (默认是PENDING)如果不是PENDING就会抛出异常,而且在这个方法里面mStatus会赋值成RUNNING(所以execute方法只能执行一次)。
然后就执行onPreExecute方法(上面讲过这是执行前做的准备工作),最后调用exec.execute(mFuture);执行线程任务。
要知道怎么执行线程池任务要看sDefaultExecutor代码。
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
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);
}
}
}
sDefaultExecutor 实际上就是SerialExecutor ,SerialExecutor 实现了Executor 接口,在执行execute,任务加入了ArrayDeque数组,mActive是当前在执行的任务,执行的任务会加入THREAD_POOL_EXECUTOR线程池里执行,可以看到当前有任务执行时,不会执行这个任务,而且mTasks会循环的把加入的任务串行的一个一个的执行完。
那么一个异步任务是如果个个步骤的一次调用的?首先回到构造方法来看下:
public AsyncTask() {
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(result);
}
};
mFuture = new FutureTask(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);
}
}
};
}
mFuture就是上面看到的线程池执行的任务(future基本用处可以看这里Future),当mFuture被SerialExecutor执行时,会执行其mWorker。它在调用的时候,先把mTaskInvoked设置为true表示已调用,设置线程优先级,然后才执行doInBackground()方法,并执行postResult发送其返回的结果。postResult代码如下:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
postResult利用getHandler获取到Handler 然后发标记为MESSAGE_POST_RESULT的消息和doInBackground返回的Result给InternalHandler,
InternalHandler代码如下:
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;
}
}
}
可以看到InternalHandler 有两种消息,一种是MESSAGE_POST_PROGRESS用来调用onProgressUpdate方法的,也就是之前说的更新进度方法,另外是MESSAGE_POST_RESULT,调用了finish方法。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
isCancelled是判断当前task是否取消了,取消了就调用onCancelled方法来回调result,没取消就调用onPostExecute返回result。
整个流程就到这里了。