簡(jiǎn)介
當(dāng)android應(yīng)用啟動(dòng)的時(shí)候會(huì)啟動(dòng)一條主線程让虐,這個(gè)主線程負(fù)責(zé)向UI組件分發(fā)事件(包括繪制事件)慷妙,所以當(dāng)在主線程執(zhí)行耗時(shí)任務(wù)你都會(huì)阻塞UI線程考赛,導(dǎo)致事件停止分發(fā)(包括繪制事件),如果UI線程blocked的時(shí)間太長(zhǎng)(大約超過(guò)5秒)槐瑞,用戶就會(huì)看到ANR(application not responding)的對(duì)話框犹芹,所以當(dāng)我們執(zhí)行耗時(shí)任務(wù)的時(shí)候要在子線程來(lái)做(訪問(wèn)網(wǎng)絡(luò)崎页、數(shù)據(jù)庫(kù)查詢等等),所以主線程和子線程的通信就成為了關(guān)鍵腰埂,android提供了handler可以讓主線程和子線程通信飒焦,其中AsyncTask是通過(guò)handler和線程池來(lái)實(shí)現(xiàn)的輕量化異步任務(wù)的工具。(以下所有源碼來(lái)自23版本)
用法
可以看下AsyncTask類的簡(jiǎn)化代碼
public abstract class AsyncTask<Params, Progress, Result> {
abstract Result doInBackground(Params... params);
void onPreExecute() {}
protected void onProgressUpdate(Progress... values) {}
protected void onPostExecute(Result result) {}
}
可以看到AsyncTask是個(gè)抽象類盐固,有個(gè)唯一的抽象方法是doInBackground和三個(gè)泛型Params, Progress, Result,三個(gè)泛型分別是doInBackground丈挟,onProgressUpdate刁卜,onPostExecute方法的形參類型。實(shí)現(xiàn)AsyncTask一般要實(shí)現(xiàn)代碼中的那幾個(gè)方法曙咽,現(xiàn)在讓我們看看這幾個(gè)方法的用處蛔趴。
- doInBackground(Params... params):
就像它的名字那樣,是在子線程執(zhí)行的例朱,所以耗時(shí)任務(wù)寫(xiě)這里面 - onPreExecute():
在execute(Params... params)被調(diào)用后立即執(zhí)行孝情,一般用來(lái)在執(zhí)行后臺(tái)任務(wù)前對(duì)UI做一些標(biāo)記,在主線程執(zhí)行 - onProgressUpdate(Progress... values):
在調(diào)用publishProgress(Progress... values)時(shí)洒嗤,此方法被執(zhí)行箫荡,直接將耗時(shí)任務(wù)進(jìn)度信息更新到UI組件上,在主線程執(zhí)行 - onPostExecute(Result result):
當(dāng)后臺(tái)異步任務(wù)結(jié)束渔隶,此方法將會(huì)被調(diào)用羔挡,result為doInBackground返回的結(jié)果,在主線程執(zhí)行
在實(shí)現(xiàn)完AsyncTask抽象類后調(diào)用execute(Params... params)方法來(lái)執(zhí)行異步任務(wù)间唉。
注意事項(xiàng)
- 當(dāng)AsyncTask為非靜態(tài)內(nèi)部類時(shí)绞灼,AsyncTask實(shí)例會(huì)帶有activity的引用,當(dāng)activity銷毀時(shí)AsyncTask后臺(tái)線程還在執(zhí)行呈野,會(huì)導(dǎo)致Activity無(wú)法被回收低矮,引起內(nèi)存泄露。
- AsyncTask的版本差異問(wèn)題被冒,版本實(shí)現(xiàn)AsyncTask的線程池會(huì)有所不一樣军掂,這樣導(dǎo)致版本之中執(zhí)行AsyncTask的效果不同轮蜕,可能需要因?yàn)檫@個(gè)做版本兼容。
在Android 1.6到2.3是并行的良姆,有5個(gè)核心線程的線程池(ThreadPoolExecutor)負(fù)責(zé)調(diào)度任務(wù)肠虽。但Android 3.0開(kāi)始,AsyncTask改成了串行玛追,默認(rèn)的Executor被指定為SERIAL_EXECUTOR税课。不過(guò)可以通過(guò)executeOnExecutor()方法自己傳入線程池來(lái)實(shí)現(xiàn)并行,也可以調(diào)用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,...)利用AsyncTask.THREAD_POOL_EXECUTOR這個(gè)AsyncTask自己實(shí)現(xiàn)的線程池來(lái)實(shí)現(xiàn)并行任務(wù)痊剖。
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params){...}
源碼分析
因?yàn)檎{(diào)用execute方法來(lái)執(zhí)行異步任務(wù)韩玩,我們先從execute方法來(lái)分析。
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,
}
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask<Params, Progress, Result> 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;
}
看到execute實(shí)際是調(diào)用了executeOnExecutor()傳進(jìn)去了sDefaultExecutor的默認(rèn)線程池陆馁,當(dāng)調(diào)用了executeOnExecutor時(shí)找颓,mStatus (默認(rèn)是PENDING)如果不是PENDING就會(huì)拋出異常,而且在這個(gè)方法里面mStatus會(huì)賦值成RUNNING(所以execute方法只能執(zhí)行一次)叮贩。
然后就執(zhí)行onPreExecute方法(上面講過(guò)這是執(zhí)行前做的準(zhǔn)備工作)击狮,最后調(diào)用exec.execute(mFuture);執(zhí)行線程任務(wù)。
要知道怎么執(zhí)行線程池任務(wù)要看sDefaultExecutor代碼益老。
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
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);
}
}
}
sDefaultExecutor 實(shí)際上就是SerialExecutor 彪蓬,SerialExecutor 實(shí)現(xiàn)了Executor 接口,在執(zhí)行execute捺萌,任務(wù)加入了ArrayDeque數(shù)組档冬,mActive是當(dāng)前在執(zhí)行的任務(wù),執(zhí)行的任務(wù)會(huì)加入THREAD_POOL_EXECUTOR線程池里執(zhí)行桃纯,可以看到當(dāng)前有任務(wù)執(zhí)行時(shí)酷誓,不會(huì)執(zhí)行這個(gè)任務(wù),而且mTasks會(huì)循環(huán)的把加入的任務(wù)串行的一個(gè)一個(gè)的執(zhí)行完态坦。
那么一個(gè)異步任務(wù)是如果個(gè)個(gè)步驟的一次調(diào)用的盐数?首先回到構(gòu)造方法來(lái)看下:
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(result);
}
};
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 occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
mFuture就是上面看到的線程池執(zhí)行的任務(wù)(future基本用處可以看這里Future),當(dāng)mFuture被SerialExecutor執(zhí)行時(shí)伞梯,會(huì)執(zhí)行其mWorker娘扩。它在調(diào)用的時(shí)候,先把mTaskInvoked設(shè)置為true表示已調(diào)用壮锻,設(shè)置線程優(yōu)先級(jí)琐旁,然后才執(zhí)行doInBackground()方法,并執(zhí)行postResult發(fā)送其返回的結(jié)果猜绣。postResult代碼如下:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
postResult利用getHandler獲取到Handler 然后發(fā)標(biāo)記為MESSAGE_POST_RESULT的消息和doInBackground返回的Result給InternalHandler灰殴,
InternalHandler代碼如下:
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;
}
}
}
可以看到InternalHandler 有兩種消息,一種是MESSAGE_POST_PROGRESS用來(lái)調(diào)用onProgressUpdate方法的,也就是之前說(shuō)的更新進(jìn)度方法牺陶,另外是MESSAGE_POST_RESULT伟阔,調(diào)用了finish方法。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
isCancelled是判斷當(dāng)前task是否取消了掰伸,取消了就調(diào)用onCancelled方法來(lái)回調(diào)result皱炉,沒(méi)取消就調(diào)用onPostExecute返回result。
整個(gè)流程就到這里了狮鸭。