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

Android 非同步任務利器:AsyncTask 完整用法

編輯:關於 Android 程式設計

Android 強制採單線程模型,有兩條鐵則:不要阻塞 UI 線程;只能從 UI 線程存取 Android UI 工具包。UI 操作本身並非線程安全,因此背景運算與介面更新必須妥善分工。

App 啟動時,系統會同時起一條主線程,負責處理按鍵、觸控、繪圖等事件並分派給對應元件,因此主線程又稱 UI 線程。若在此做網路請求或大量計算,畫面就會卡住甚至 ANR。

兩種非同步機制

Handler:為每個任務建立一條新線程,完成後透過 Handler 向 UI 線程送訊息以更新介面。彈性最高,但樣板程式碼多。

AsyncTask:把建立非同步任務的過程封裝起來,不必自己寫線程與 Handler,就能完成同樣的事。

AsyncTask 的三個泛型

public abstract class AsyncTask<Params, Progress, Result>

Params 是啟動任務時傳入的輸入參數型別;Progress 是背景任務執行期間回報的進度型別;Result 是背景運算的結果型別。範例中若為 AsyncTask<String, Integer, String>,代表傳入網址字串、以整數回報百分比、最後回傳網頁內容字串。

五個關鍵方法

execute(Params... params):由呼叫端觸發,開始執行非同步任務。

onPreExecute():在 execute 之後立刻執行,跑在 UI 線程,常用於顯示進度條、禁用按鈕等前置狀態。

doInBackground(Params... params):在 onPreExecute 之後執行,跑在工作線程,是真正做耗時工作的所在。執行中可呼叫 publishProgress() 發布進度,並以 isCancelled() 檢查是否已被取消。

onProgressUpdate(Progress... values):在 publishProgress 被呼叫時觸發,跑在 UI 線程,可直接更新進度元件。

onPostExecute(Result result):背景工作結束後觸發,接收 doInBackground 的回傳值,跑在 UI 線程,用來把結果呈現在畫面上。

自訂一個非同步任務

public class TestAsyncTask extends AsyncTask<String, Integer, String> {

    static final String TAG = "testAsyncTask";
    AsyncTaskCallback cb = null;

    public static final int PRE_EVENT   = 1;
    public static final int POST_EVENT  = 2;
    public static final int CACEL_EVENT = 3;

    public static interface AsyncTaskCallback {
        void onAsyncResult(int e, String s);   // 顯示結果
        void onAsyncProcess(Integer pi);       // 顯示進度
    }

    public TestAsyncTask(Context c, AsyncTaskCallback cb) {
        this.cb = cb;
    }

    @Override
    protected void onPreExecute() {
        cb.onAsyncResult(PRE_EVENT, "loading...");
    }

    @Override
    protected void onPostExecute(String result) {
        cb.onAsyncResult(POST_EVENT, result);
    }

    @Override
    protected void onCancelled() {
        cb.onAsyncResult(CACEL_EVENT, "cancle loading");
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        cb.onAsyncProcess(values[0]);
    }

    @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[512];
                int count = 0, length = -1;

                while ((length = is.read(buf)) != -1) {
                    baos.write(buf, 0, length);
                    count += length;
                    // 發布進度,隨後 onProgressUpdate 會被呼叫
                    publishProgress((int) ((count / (float) total) * 100));
                    Thread.sleep(100);      // 為了看清楚動畫,僅供示範
                }
                return new String(baos.toByteArray(), "utf-8");
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return null;
    }
}

在 Activity 中使用

AsyncTaskCallback cb = new AsyncTaskCallback() {
    @Override
    public void onAsyncResult(int e, String s) {
        Message msg = Message.obtain();
        msg.what = 1;
        msg.arg1 = e;
        msg.obj  = s;
        testH.sendMessage(msg);
    }

    @Override
    public void onAsyncProcess(Integer pi) {
        Message msg = Message.obtain();
        msg.what = 2;
        msg.obj  = pi;
        testH.sendMessage(msg);
    }
};

execute.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        // 每次都必須 new 一個新實例
        task = new TestAsyncTask(MainActivity.this.getApplicationContext(), cb);
        task.execute("https://www.example.com/");
        execute.setEnabled(false);
        cancel.setEnabled(true);
    }
});

cancel.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        task.cancel(true);      // 觸發 onCancelled()
    }
});

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/execute"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="execute" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="cancel" />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:progress="0"
        android:max="100" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/text_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

實務上必須知道的限制

一個實例只能執行一次。重複呼叫 execute 會拋出 IllegalStateException,所以每次點擊都要 new 一個新的 AsyncTask。

預設是序列執行。從 Android 3.x(Honeycomb)起,同版本內多個 AsyncTask 會排隊依序執行,除非改用 executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params)。若想併發下載,必須明確指定。

與 Activity 生命週期脫鉤。若在背景任務執行中旋轉螢幕,Activity 重建後原任務的參照就斷了,結果會丟失。實務上應改用 ViewModel、Retained Fragment,或直接改用 Loaders。

已被取代。Android 11(API 30)起 AsyncTask 已被標記為 deprecated。新專案請改用 Kotlin 協程、WorkManager(適合可延後、需保證完成的工作)或 RxJava。理解 AsyncTask 的設計概念仍有價值,但 production 程式碼應選用現行方案。

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