Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

詳解 Android 中 AsyncTask 的使用與源碼原理

編輯:關於 Android 程式設計

不是自己不想總結,而是這篇部落格總結得太好了,自己估計總結不到這麼全,所以轉來分享,感謝原博主的共享精神。開篇如下:

在 Android 中實現異步任務機制有兩種方式:Handler 和 AsyncTask。

Handler 模式需要為每一個任務創建一個新線程,任務完成後透過 Handler 實例向 UI 線程發送消息、完成界面更新。這種方式對整個過程的控制比較精細,但也有缺點,例如程式碼相對臃腫,在多個任務同時執行時不易對線程進行精確控制。

為了簡化操作,Android 1.5 提供了工具類 android.os.AsyncTask,它讓創建異步任務變得更簡單,不再需要編寫任務線程和 Handler 實例即可完成相同的任務。

先來看看 AsyncTask 的定義:

public abstract class AsyncTask<Params, Progress, Result> { ... }

三種泛型類型分別代表「啟動任務執行的輸入參數」「後台任務執行的進度」「後台計算結果的類型」。在特定場合下並非所有類型都會用到,如果沒用到,可以用 java.lang.Void 類型代替。

一個異步任務的執行一般包括以下幾個步驟:

1.execute(Params... params):執行一個異步任務,需要我們在程式碼中呼叫此方法,觸發異步任務的執行。
2.onPreExecute():在 execute() 被呼叫後立即執行,一般用來在執行後台任務前對 UI 做一些標記。
3.doInBackground(Params... params):在 onPreExecute() 完成後立即執行,用於執行較為耗時的操作,此方法接收輸入參數並返回計算結果,過程中可呼叫 publishProgress(Progress... values) 來更新進度。
4.onProgressUpdate(Progress... values):在呼叫 publishProgress() 時執行,直接將進度資訊更新到 UI 組件上。
5.onPostExecute(Result result):當後台操作結束時呼叫,計算結果作為參數傳入,直接把結果顯示到 UI 組件上。

使用時有幾點需要格外注意:

1. 異步任務的實例必須在 UI 線程中創建。
2. execute(Params... params) 方法必須在 UI 線程中呼叫。
3. 不要手動呼叫 onPreExecute()、doInBackground()、onProgressUpdate()、onPostExecute() 這幾個方法。
4. 不能在 doInBackground() 中更改 UI 組件的資訊。
5. 一個任務實例只能執行一次,執行第二次將會拋出異常。

接下來看看如何使用 AsyncTask 執行異步任務操作。先看看 MainActivity.java 的程式碼:

public class MainActivity extends Activity {
 private static final String TAG = "ASYNC_TASK";
 private Button execute;
 private Button cancel;
 private ProgressBar progressBar;
 private TextView textView;
 private MyTask mTask;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 execute = (Button) findViewById(R.id.execute);
 execute.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 //注意每次需 new 一個實例,新建的任務只能執行一次,否則會出現異常
 mTask = new MyTask();
 mTask.execute("https://www.baidu.com");
 execute.setEnabled(false);
 cancel.setEnabled(true);
 }
 });
 cancel = (Button) findViewById(R.id.cancel);
 cancel.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 //取消一個正在執行的任務,onCancelled 方法將會被調用
 mTask.cancel(true);
 }
 });
 progressBar = (ProgressBar) findViewById(R.id.progress_bar);
 textView = (TextView) findViewById(R.id.text_view);
 }

 private class MyTask extends AsyncTask {
 //onPreExecute 方法用於在執行後台任務前做一些 UI 操作
 @Override
 protected void onPreExecute() {
 Log.i(TAG, "onPreExecute() called");
 textView.setText("loading...");
 }

 //doInBackground 方法內部執行後台任務,不可在此方法內修改 UI
 @Override
 protected String doInBackground(String... params) {
 try {
 HttpClient client = new DefaultHttpClient();
 HttpGet get = new HttpGet(params[0]);
 HttpResponse response = client.execute(get);
 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
 HttpEntity entity = response.getEntity();
 InputStream is = entity.getContent();
 long total = entity.getContentLength();
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 byte[] buf = new byte[1024];
 int count = 0;
 int length = -1;
 while ((length = is.read(buf)) != -1) {
 baos.write(buf, 0, length);
 count += length;
 //調用 publishProgress 公布進度,最後 onProgressUpdate 方法將被執行
 publishProgress((int) ((count / (float) total) * 100));
 //為了演示進度,休眠 500 毫秒
 Thread.sleep(500);
 }
 return new String(baos.toByteArray(), "gb2312");
 }
 } catch (Exception e) {
 Log.e(TAG, e.getMessage());
 }
 return null;
 }

 //onProgressUpdate 方法用於更新進度資訊
 @Override
 protected void onProgressUpdate(Integer... progresses) {
 progressBar.setProgress(progresses[0]);
 textView.setText("loading..." + progresses[0] + "%");
 }

 //onPostExecute 方法用於執行完後台任務後更新 UI、顯示結果
 @Override
 protected void onPostExecute(String result) {
 textView.setText(result);
 execute.setEnabled(true);
 cancel.setEnabled(false);
 }

 //onCancelled 方法用於在取消執行中的任務時更改 UI
 @Override
 protected void onCancelled() {
 textView.setText("cancelled");
 progressBar.setProgress(0);
 execute.setEnabled(true);
 cancel.setEnabled(false);
 }
 }
}

因為需要訪問網絡,所以還要在 AndroidManifest.xml 中加入訪問網絡的權限。

可以看到,AsyncTask 的初始狀態為 PENDING(待定),RUNNING 代表執行,FINISHED 代表結束,這幾種狀態在 AsyncTask 一次生命週期內的很多地方被使用,非常重要。

程式碼中涉及到三個陌生的變量:mWorker、sExecutor、mFuture,我們也來看看它們的廬山真面目。

mWorker 實際上是 AsyncTask 的一個抽象內部類的實現對象實例,它實現了 Callable<Result> 接口中的 call() 方法:

private static abstract class WorkerRunnable implements Callable {
 Params[] mParams;
}

而 mFuture 實際上是 java.util.concurrent.FutureTask 的實例,FutureTask 是一個可中途取消的、用於異步計算的類:

public class FutureTask implements RunnableFuture { ... }

public interface RunnableFuture extends Runnable, Future {
 void run();
}

下面是 mWorker 和 mFuture 實例在 AsyncTask 中的體現:

private final WorkerRunnable mWorker;
private final FutureTask mFuture;

public AsyncTask() {
 mWorker = new WorkerRunnable() {
 //call 方法被調用後,將設置優先級為後台級別,然後調用 AsyncTask 的 doInBackground 方法
 public Result call() throws Exception {
 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
 return doInBackground(mParams);
 }
 };
 //在 mFuture 實例中,將會調用 mWorker 做後台任務,完成後會調用 done 方法
 mFuture = new FutureTask(mWorker) {
 @Override
 protected void done() {
 Message message;
 Result result = null;
 try {
 result = 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) {
 //發送取消任務的消息
 message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
 new AsyncTaskResult(AsyncTask.this, (Result[]) null));
 message.sendToTarget();
 return;
 } catch (Throwable t) {
 throw new RuntimeException("An error occured while executing doInBackground()", t);
 }
 //發送顯示結果的消息
 message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
 new AsyncTaskResult(AsyncTask.this, result));
 message.sendToTarget();
 }
 };
}

我們看到,mFuture 實例對象的 done() 方法中,如果捕捉到 CancellationException 類型異常,則發送一條「MESSAGE_POST_CANCEL」消息;如果順利執行,則發送一條「MESSAGE_POST_RESULT」消息,而消息都與一個 sHandler 對象關聯。這個 sHandler 實例實際上是 AsyncTask 內部類 InternalHandler 的實例,而 InternalHandler 正是繼承了 Handler:

private static final int MESSAGE_POST_RESULT = 0x1; //顯示結果
private static final int MESSAGE_POST_PROGRESS = 0x2; //更新進度
private static final int MESSAGE_POST_CANCEL = 0x3; //取消任務
private static final InternalHandler sHandler = new InternalHandler();

private static class InternalHandler extends Handler {
 @Override
 public void handleMessage(Message msg) {
 AsyncTaskResult result = (AsyncTaskResult) msg.obj;
 switch (msg.what) {
 case MESSAGE_POST_RESULT:
 //調用 AsyncTask.finish 方法
 result.mTask.finish(result.mData[0]);
 break;
 case MESSAGE_POST_PROGRESS:
 //調用 AsyncTask.onProgressUpdate 方法
 result.mTask.onProgressUpdate(result.mData);
 break;
 case MESSAGE_POST_CANCEL:
 //調用 AsyncTask.onCancelled 方法
 result.mTask.onCancelled();
 break;
 }
 }
}

可以看到,處理消息時遇到「MESSAGE_POST_RESULT」會呼叫 AsyncTask 中的 finish() 方法,來看看它的定義:

private void finish(Result result) {
 if (isCancelled()) result = null;
 onPostExecute(result); //調用 onPostExecute 顯示結果
 mStatus = Status.FINISHED; //改變狀態為 FINISHED
}

原來 finish() 方法是負責呼叫 onPostExecute(Result result) 顯示結果並改變任務狀態的。

另外,在 mFuture 對象的 done() 方法裡,構建消息時包含了一個 AsyncTaskResult 類型的對象,而在 sHandler 的 handleMessage() 方法裡,使用 msg.obj 取出這個對象。這個 AsyncTaskResult 是 AsyncTask 的一個內部類,用來包裝執行結果:

private static class AsyncTaskResult {
 final AsyncTask mTask;
 final Data[] mData;
 AsyncTaskResult(AsyncTask task, Data... data) {
 mTask = task;
 mData = data;
 }
}

可以看到這個 AsyncTaskResult 封裝了一個 AsyncTask 的實例和某種類型的數據集。構建消息時:

//發送取消任務的消息
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
 new AsyncTaskResult(AsyncTask.this, (Result[]) null));
message.sendToTarget();
//發送顯示結果的消息
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
 new AsyncTaskResult(AsyncTask.this, result));
message.sendToTarget();

處理消息時則這樣使用這個對象:

result.mTask.finish(result.mData[0]);
result.mTask.onProgressUpdate(result.mData);

概括來說,當我們呼叫 execute(Params... params) 方法後,execute 會呼叫 onPreExecute(),然後由 ThreadPoolExecutor 實例 sExecutor 執行一個 FutureTask 任務,這個過程中 doInBackground() 將被呼叫。如果被覆寫的 doInBackground() 中呼叫了 publishProgress(),則透過 InternalHandler 實例 sHandler 發送一條 MESSAGE_POST_PROGRESS 消息、更新進度,sHandler 處理時 onProgressUpdate() 被呼叫;如果遇到異常,則發送 MESSAGE_POST_CANCEL 消息、取消任務,sHandler 處理時 onCancelled() 被呼叫;如果執行成功,則發送 MESSAGE_POST_RESULT 消息、顯示結果,sHandler 處理時 onPostExecute() 被呼叫。

經過上面的介紹,相信朋友們都已經認識到 AsyncTask 的本質了——它對 Thread + Handler 做了良好封裝,降低了開發者處理問題的複雜度、提高了開發效率,希望能多多體會一下。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved