AsynTask介绍
AsyncTask是一个抽象类,有三个泛型参数,四个方法。
- Params
需要传入的参数 - Progress
后台任务在执行时,如果需要在界面上显示当前进度,则就用Progress指定的泛型作为进度单位。 - Result
指定的泛型作为返回的类型。
- 此方法会在后台任务执行前被调用,用于进行一些准备工作
onPreExecute() - 此方法中定义要执行的后台任务,在这个方法中可以调用publishProgress来更新任务进度
onPreExecute() - 由publishProgress内部调用,表示任务进度更新
onPreExecute() - 后台任务执行完毕后,此方法会被调用,参数即为后台任务的返回结果
onPostExecute(Result result)
源码分析
- 创建AsynTask
public AsyncTask() {
mWorker = new WorkerRunnable() {
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(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);
}
}
};
}
在构造方法中初始化mWorker和mFuture
private static abstract class WorkerRunnable implements Callable {
Params[] mParams;
}
public interface Callable {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
- mWorker实现Callable的call方法,调用了doInBackground(),并调用 postResult(result)。
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
/*package*/ Handler target;
public void sendToTarget() {
target.sendMessage(this);
}
最终通过Handler发送了一个消息
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
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;
}
}
}
这里可以看到getHandlerf返回了一个InternalHandler对象,在InternalHandler中对消息进行了处理,
如果MESSAGE_POST_RESULT调用finish
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
- 在finish方法中调用了onPostExecute();
- 如果为 MESSAGE_POST_PROGRESS则调用onProgressUpdate()方法
- 在看看mFuture初始化的时候会讲mWorker作为参数传入,在postResultIfNotInvoked()方法中调用postResult()。
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
在回到开始我们调用execute()方法
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;
}
最终调用executeOnExecutor()方法,在这个方法中首先判断了mStatus状态,如果不是PENDING则抛出异常,否则设置他的状态未运行状态,并调用 onPreExecute(); 因为AsynTash在主线程调用,所以onPreExecute();方法可以进行一些UI改变, 然后设置mWorker的mParams值,最后调用exec的execute方法,将mFuture传入。
其中exec我们可以知道是sDefaultExecutor。
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实际上是一个串行的线程池,一个进程中所有的AsyncTask全部都在这个线程池中执行。
首先系统会把AsyncTask的参数封装为FutureTask对象,FutureTask是一个并发类,在这里它充当了Runnable的作用。
调用他的execute方法会先把FutureTask对象插入到任务队列mTask中,如果这时没有正在活动的任务,那么就会调用SeriaExecutor的scheduleNext()类执行下个任务