Asynctask是一種輕量級異步任務(wù)類,任務(wù)是在線程池中執(zhí)行后臺任務(wù)的,并將結(jié)果返回到UI界面。它封裝了handler和thread,但是asynctask不適合特別耗時的任務(wù),耗時任務(wù)建議使用線程池。
1.方法介紹
核心方法四個:onPreExecute()、doInBackground()、onProgressUpdate()、onPostExecute(),這四個方法除了doInBackground()其余都存在了主線程
2.注意點
1)Asynctask類初始加載應(yīng)該在主線程,android5.0以后activitythread的main方法中,已經(jīng)將這個類初始化了
2)Asynctask創(chuàng)建對象,也應(yīng)該在主線程
3)execute方法要在主線程
4)不能手動調(diào)用asynctask的四個核心方法
5)一個Asynctask對象,只能調(diào)用一次execute方法
6)android1.6以前是串行,3.0以后既可以串行也可以并行
3.源碼分析

首先來解釋一下,剛創(chuàng)建完成asynctask對象后,會執(zhí)行execute()方法,然后執(zhí)行onpreExecute(),接下來asynctask里面的線程池就開始工作了。在Asynctask創(chuàng)建的同時,會將doInBackground()這個方法體封裝進一個callable當中,然后再進行封轉(zhuǎn)到并發(fā)類Futuretask中,代碼如下:
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(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);
}
}
};
}
線程池在執(zhí)行execute方法的時候,會先將任務(wù)添加到隊列中,如果當前沒有活動的任務(wù),就會執(zhí)行scheduleNext()來執(zhí)行下一個任務(wù)。從這一個角度來看,asynctask是串行的。代碼如下:
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
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);
}
}
}
在執(zhí)行Futuretask的run方法的時候,最后會調(diào)用到WorkerRunnable的call方法,進而執(zhí)行doinbackground方法,會把返回值傳給postResult方法,它會通過sHandler發(fā)送一個消息,handler處理消息會讓Asynctask執(zhí)行finish方法
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}