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

AsyncTask 的基本用法詳解

編輯:關於 Android 程式設計

開發 Android 應用時必須遵守單線程模型:Android 的 UI 操作並非線程安全,且這些操作都必須在 UI 線程中執行。在單線程模型中要牢記兩條法則:

1. 不要阻塞 UI 線程。

2. 確保只在 UI 線程中訪問 Android UI 工具包。

程式第一次啟動時,Android 會啟動一個主線程(Main Thread),負責處理與 UI 相關的事件(如按鍵、觸控、繪圖)並分發給對應元件,因此主線程又稱 UI 線程。例如從網路抓取網頁並顯示到 TextView,這種涉及網络的操作必須另開線程,但在背景線程中不能直接呼叫 TextView.setText(),因為其他線程無法直接訪問 UI 線程的成員。

為了解決這個問題,Android 1.5 提供了工具類別 AsyncTask,讓需要與使用者介面互動的長時間任務變得更簡單。它相對輕量,適合簡單的異步處理,不需另外借助線程與 Handler。AsyncTask 是抽象類別,定義了三種泛型:Params(啟動任務的輸入參數,如 HTTP 請求的 URL)、Progress(後台任務執行的百分比)、Result(後台任務的最終回傳結果,如 String)。

四個執行步驟與回呼方法

1)子類化 AsyncTask。

2)實作以下一個或多個方法(不可由應用程式主動呼叫):

onPreExecute():在執行實際後台操作前由 UI 線程呼叫,可做準備工作,例如在介面顯示進度條。

doInBackground(Params...):在 onPreExecute 之後執行,運行於後台線程,負責耗時的計算工作,可呼叫 publishProgress() 更新進度;這是抽象方法,子類必須實作。

onProgressUpdate(Progress...):在 publishProgress 被呼叫後由 UI 線程觸發,用以在介面展示進展。

onPostExecute(Result):在 doInBackground 完成後由 UI 線程呼叫,把結果傳回 UI 線程。

使用 AsyncTask 必須遵守的準則

1)Task 的實例必須在 UI 線程中建立。

2)execute 方法必須在 UI 線程中呼叫。

3)不要手動呼叫 onPreExecute、onPostExecute、doInBackground、onProgressUpdate。

4)同一個 Task 只能執行一次,否則會出現異常。

此外,doInBackground 與 onPostExecute 的參數需對應 AsyncTask 宣告的泛型:第一個是 doInBackground 的輸入參數、第二個是進度參數、第三個是 doInBackground 的回傳(也是 onPostExecute 的傳入)參數。

下載網路圖片的範例

public class MainActivity extends Activity {
    private Button button;
    private ImageView imageview;
    private String image_path = "https://d.hiphotos.baidu.com/image/w%3D2048/sign=72da8b71d62a60595210e61a1c0c369b/caef76094b36acaf0d08f1447dd98d1000e99c99.jpg";
    private ProgressDialog dialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog = new ProgressDialog(this);
        dialog.setTitle("提示信息");
        dialog.setMessage("正在下載,請稍等。。。。");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 橫向進度條
        dialog.setCancelable(false);                              // 下載完成前不消失
        button = (Button) this.findViewById(R.id.but);
        imageview = (ImageView) this.findViewById(R.id.image);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                new MyTask().execute(image_path);
            }
        });
    }

    public class MyTask extends AsyncTask<String, Integer, Bitmap> {
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.show();
        }
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            dialog.setProgress(values[0]);
        }
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            InputStream inputStream = null;
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(params[0]);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    inputStream = httpResponse.getEntity().getContent();
                    long file_length = httpResponse.getEntity().getContentLength(); // 檔案總長度
                    int len = 0;
                    byte[] data = new byte[1024];
                    int total_length = 0;
                    while ((len = inputStream.read(data)) != -1) {
                        total_length += len;
                        int value = (int) ((total_length / (float) file_length) * 100);
                        publishProgress(value); // 發布進度
                        outputStream.write(data, 0, len);
                    }
                    byte[] result = outputStream.toByteArray();
                    bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return bitmap;
        }
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            dialog.dismiss();
            imageview.setImageBitmap(result);
        }
    }
}

這個範例完整示範了 AsyncTask 的用法:在 doInBackground 中下載圖片並透過 publishProgress 回報進度,再由 onPostExecute 把結果設定到 ImageView,全程不必手動管理線程與 Handler。

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