AsyncTask机制
AsyncTask必需会用到的三个方法
1, onPreExeCute
2, doInBackground
3, onPostExecute
AsyncTask的execute方法,开始执行异步任务,在此方法体中
public final AsyncTask<Params, Progress, Result> execute(Params... params) { ... mStatus = Status.RUNNING; //调用onPreExecute方法 onPreExecute(); //把参数赋值给mWorker对象 mWorker.mParams = params; //线程池对象执行mFuture sExecutor.execute(mFuture); return this; }
mWorker是什么类型?,在AsyncTask的构造方法中
mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return doInBackground(mParams); } };
然后把mWorker对象封装至FutureTask对象
mFuture = new FutureTask<Result>(mWorker)
在FutureTask的构造中,又把mWorker封装给Sync对象
public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); sync = new Sync(callable); }
在Sync的构造方法中
Sync(Callable<V> callable) { //这里的callable就是mWorker this.callable = callable; }
线程池执行mFuture对象,此对象是FutureTask的对象,而FutureTask实现了Runnable接口
public final AsyncTask<Params, Progress, Result> execute(Params... params) { ... //线程池对象执行mFuture sExecutor.execute(mFuture); ...
}
mFuture的run方法被调用了
public void run() { sync.innerRun(); }
在innerRun方法中,调用了callable的call方法,但是在sync被new出来的时候,在构造方法中就已经把mWorker赋值给了callable,所以实际上是调用mWorker的call方法
void innerRun() { ... //调用mWorker的call() result = callable.call(); set(result); ... }
mWorker的call在mWorker被new出来时就已经重写了
mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { ... //在子线程中调用了doInBackground方法 return doInBackground(mParams); } };
call方法调用完毕后,得到doInBackground所返回的result
void innerRun() { ... result = callable.call(); //返回的result传入了set方法 set(result); ... }
set方法体
protected void set(V v) { sync.innerSet(v); }
innerSet方法体
if (compareAndSetState(s, RAN)) { result = v; releaseShared(0); //关键的done方法 done(); return; }
innerSet方法是属于FutureTask类的,那么done方法也是调用FutureTask类的,这个done方法定义的地方,在AsyncTask.java的构造方法里
mFuture = new FutureTask<Result>(mWorker) { //此处重写done方法 @Override protected void done() { //获取doInbackground方法返回的结果 result = get(); //创建一个消息 message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(AsyncTask.this, result)); //把这条消息发送给创建这个消息的Handler:target.sendMessage(this) message.sendToTarget(); } };
然后sHandler的handlerMessage被触发
public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: //调用finish方法 result.mTask.finish(result.mData[0]); break; } }
finish的方法体
private void finish(Result result) { if (isCancelled()) result = null; //调用onPostExecute方法,并传入结果 onPostExecute(result); mStatus = Status.FINISHED;