Asynctask解析以及注意事项(三)

2014-11-24 11:01:08 · 作者: · 浏览: 2
}
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
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,
}
/** @hide Used to force static handler to be created. */
public static void init() {
sHandler.getLooper();
}
/** @hide */
public static void setDefaultExecutor(Executor exec) {
sDefaultExecutor = exec;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
//初始化mWorker并复写call方法,后面会介绍什么时候调用
mWorker = new WorkerRunnable() {
// 这个方法就是当你嗲用excutor.excute()方法后执行的方法。至于是如何执行的,我们后面会分析
public Result call() throws Exception {
mTaskInvoked.set(true);
// 将线程优先级设置为后台线程,默认和主线程优先级一样,如果不这样做,也会降低程序性能.因为会优先
// 抢占cpu资源.所以,如果你在程序中不使用asyncTask而是自己new 一条线程出来,记得把线程的优先级设置为
// 后台线程
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//这个地方调用了我们自己实现的doInBackground
return postResult(doInBackground(mParams));
}
};
// 用mWorker创建一个可取消的异步计算任务
mFuture = new FutureTask(mWorker) {
@Override
// 当任务不管是正常终止、异常或取消而完成的,都回调此方法, 即isDone()为true时,isDone不管成功还是失败都
// 返回true
protected void done() {
try {
// 如果当前的task没有被invoke,就被finish掉
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 void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
// 当doInBackground结束了,调用PostResult发布结果
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
// 获得当前的状态
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param pa