AsyncTask簡介
AsyncTask可以正確道媚、方便的使用UI線程,執(zhí)行后臺(tái)任務(wù)并且在UI線程中展示執(zhí)行結(jié)果消痛。理想情況下AsyncTask應(yīng)該用于短期操作(幾秒左右)税产。如果線程長期運(yùn)行摊灭,建議使用線程池咆贬。
AsyncTask參數(shù)
AsyncTask是一個(gè)泛型抽象類,提供了Params帚呼、Progress和Result這三個(gè)泛型參數(shù)。
- Params:任務(wù)執(zhí)行時(shí)的參數(shù)類型皱蹦。
- Progress:后臺(tái)任務(wù)執(zhí)行的進(jìn)度類型煤杀。
- Result:后臺(tái)任務(wù)返回的結(jié)果類型。
AsyncTask核心方法
- onPreExecute():UI線程執(zhí)行沪哺。任務(wù)執(zhí)行前調(diào)用沈自,通常用于做一些準(zhǔn)備工作。
- doInBackground(Params...params):線程池中執(zhí)行辜妓。將AsyncTask任務(wù)的執(zhí)行結(jié)果返回給onPostExecute()方法處理枯途。如果調(diào)用了publishProgress(Progress...values)則會(huì)執(zhí)行onProgressUpdate(Progress...values)。
- onProgressUpdate(Progress...values):UI線程執(zhí)行籍滴。后臺(tái)任務(wù)調(diào)用publishProgress(Progress...values)進(jìn)度發(fā)生改變時(shí)執(zhí)行酪夷。
- onPostExecute(Result result):處理doInBackground()返回的Result。
使用舉例
class DownloadFileTask extends AsyncTask<URL,Integer,Long>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
showDialog("Downloaded " + aLong + "bytes");
}
@Override
protected void onProgressUpdate(Integer... values) {
setProgerssPercent(values[0]);
}
@Override
protected Long doInBackground(URL... params) {
int length = params.length;
long totalSize = 0;
for (int i = 0 ; i < length ; i++){
totalSize += Download.downloadFile(urls[i]);
publishProgress((int)(i/(float)length) * 100);
if(isCancelled()) {
break;
}
}
return totalSize;
}
}
源碼分析
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//判斷AsyncaTask是否是空閑狀態(tài)
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)");
}
}
//改變AsyncTask任務(wù)狀態(tài)
mStatus = Status.RUNNING;
//首先在UI線程中執(zhí)行onPreExecute()
onPreExecute();
//參數(shù)封裝在WorkRunnable中
mWorker.mParams = params;
//實(shí)際執(zhí)行的是mFuture的方法
exec.execute(mFuture);
return this;
}
execute方法在UI線程執(zhí)行孽惰;這里我們看一下exec晚岭,mWorker和mFuture分別代表什么。
我們首先看一下exec
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//官網(wǎng)注釋SERIAL_EXECUTOR相當(dāng)于一個(gè)串行線程池勋功。一次執(zhí)行一個(gè)任務(wù)坦报。
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
//添加FutureTask到任務(wù)隊(duì)列中
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
//如果當(dāng)前沒有任務(wù)執(zhí)行則執(zhí)行下一個(gè)任務(wù)
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
通過上述方法我們知道AsyncTask有兩個(gè)線程池库说,THREAD_POOL_EXECUTOR主要用于執(zhí)行AsyncTask。SerialExecutor主要用于對AsyncTask任務(wù)排序片择。
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
//標(biāo)記AsyncTask為已執(zhí)行
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//工作線程中返回執(zhí)行結(jié)果潜的,在線程池中執(zhí)行
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(result);
}
};
//mFuture最終會(huì)調(diào)用mWorker的call()方法
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);
}
}
};
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
postResult方法最終會(huì)發(fā)送一個(gè)MESSAGE_POST_RESULT消息。我們看一下Handler的實(shí)現(xiàn)字管。
private static class InternalHandler extends Handler {
//將當(dāng)前線程切換回主線程
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;
}
}
}
我們看一下finish方法
private void finish(Result result) {
if (isCancelled()) {//如果任務(wù)被取消
onCancelled(result);
} else {//運(yùn)行在主線程
onPostExecute(result);
}
//最終任務(wù)的狀態(tài)都會(huì)被標(biāo)記為finished
mStatus = Status.FINISHED;
}
如果在doInBackground中調(diào)用publishProgress
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {//任務(wù)沒有被取消
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
publishProgress最終會(huì)調(diào)用onProgressUpdate()夏块,該方法在主線程中執(zhí)行。
后臺(tái)任務(wù)的執(zhí)行進(jìn)度改變的時(shí)候會(huì)調(diào)用纤掸。
總結(jié)
- 必須在UI線程上加載AsyncTask類脐供。
- 必須在UI線程上創(chuàng)建任務(wù)實(shí)例。
- execute(Params...)必須在UI線程上調(diào)用借跪。
- 不能手動(dòng)調(diào)用onPreExecute()政己、onPostExe cute(Result),doInBackground(Params...)和onProgressUpdate(Progress...)掏愁。
- 一個(gè)AsyncTask只能執(zhí)行一次歇由,再次執(zhí)行會(huì)拋異常。