一、什么是AsyncTask
AsyncTask是輕量級的用于處理簡單的異步任務(wù),不需要借助線程和Handler即可實(shí)現(xiàn)。除了之外還有以下方法解決線程不能更新UI組件問題;
- 使用Handler實(shí)現(xiàn)線程間通訊
- Activity.runOnUIThread(Runnable);
- View.post(Runnable)
- View.postDelayed(Runnable);
二、AsyncTask的使用方法
1.創(chuàng)建AsyncTask的子類,并為三個泛型指定類型的參數(shù),如果不需要制定則Void.
2.根據(jù)需要調(diào)用onPreExecute(),onPostExecute(Void aVoid),doInBackground(Void... voids),onProgressUpdate(Void... values) 等方法
3.調(diào)用AsyncTask子類的execute(Param params)執(zhí)行耗時任務(wù)
PAsyncTask pAsyncTask=new PAsyncTask();
pAsyncTask.execute("廣州");
private class PAsyncTask extends AsyncTask<String,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... strings) {
return null;
}
}
四、AsyncTask機(jī)制原理
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return 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);
}
}
};
}
此處是AsyncTask的構(gòu)造方法,創(chuàng)建了WorkerRunnable、FutureTask 的實(shí)例mWorker和mFuture,其中mWorker實(shí)現(xiàn)了call()的接口,處理doInBackground()數(shù)據(jù),mFuture則是實(shí)現(xiàn)了Runnable接口的子線程,里面調(diào)用了mWorker的call()接口
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;
}
這里先是在UI線程中執(zhí)行了onPreExecute(); exec.execute(mFuture);方法中exec是實(shí)現(xiàn)了Executor接口的(如下), r.run();是實(shí)現(xiàn)了Runable接口的mFuture子線程,具體執(zhí)行子線程實(shí)在線程隊(duì)列mTasks 中執(zhí)行。
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);
}
}
}
而后在postResult()方法中使用Handler發(fā)送消息通知UI線程
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
總結(jié):
- AsyncTask使用了FutureTask和Handler的結(jié)合,其中FutureTask實(shí)現(xiàn)了runnable接口,SerialExecutor則采用線程池的方式管理線程。
- AsyncTask在代碼上比Handler要輕量級別,但實(shí)際上比Handler更耗資源,因?yàn)锳syncTask底層是一個線程池,而Handler僅僅就是發(fā)送了一個消息隊(duì)列。但是,如果異步任務(wù)的數(shù)據(jù)特別龐大,AsyncTask線程池比Handler節(jié)省開銷,因?yàn)镠andler需要不停的new Thread執(zhí)行。
- AsyncTask的實(shí)例化只能在主線程,Handler可以隨意,只和Looper有關(guān)系,因此為什么開發(fā)中比較少用AsyncTask,而Handler+Runnable的方式更加靈活多變來適應(yīng)不同的業(yè)務(wù)需求。
五、AsyncTask注意事項(xiàng)
- 必須在UI線程中創(chuàng)建AsyncTask的實(shí)例
- 在UI線程中調(diào)用AsyncTask的execute();
- AsyncTask只能被執(zhí)行一次,多次調(diào)用會引發(fā)異常