PENDING状态:标志这个任务还没有被执行过,该状态在定义状态变量mStatus的时候就被初始化了。private volatile Status mStatus = Status.PENDING;
/**
* 执行任务的入口方法
* @param params
* @return
*/
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)");
}
}
//标志任务正在运行,如果再次调用该对象的execute方法的话,会走517行代码逻辑
mStatus = Status.RUNNING;
//任务开启前执行的方法,此时仍然在UI线程中
onPreExecute();
//保存参数
mWorker.mParams = params;
//执行任务
exec.execute(mFuture);
return this;
}
看executeOnExecutor方法,可以知道当第一次调用execute方法的时候executeOnExecutor里面的if条件是不成立的,当再次调用execute方法的时候if条件成立,然后就会抛出异常。通过观察这个方法,可以发现很多的信息,比如onPreExecute()方法就是先于其他方法执行,此时执行onPreExecute方法的时候仍在在UI线程中,所以我们可以重写这个方法以实现在执行任务之前进行其他处理的问题:比如显示加载滚动条等。接着会执行exec.exeute(mFuture)方法来在UI线程上开启一个新的线程来执行耗时的任务:也就是执行你重写的doInBackground()方法。我们知道AsyncTask的doInBackgound方法是有返回值的,这个返回值可以传给onPostExecute(Reusult result)方法,然后做具体的处理,也就是我们会从线程中获取一个返回值。
public AsyncTask() {
初始化mWorker
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
//设置控制变量为true
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//doInBackground方法再此执行
return postResult(doInBackground(mParams));
}
};
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 occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
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;
}
}
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
//onPostExecute在此处调用
onPostExecute(result);
}
//设置任务的状态为FINISHED
mStatus = Status.FINISHED;
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
查看FutureTask的源码可知在调用cancel()方法取消任务的时候会执行这个done()方法,在发生异常的时候同样会执行这一方法
未完待续,如有错误之处,欢迎批评指正