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

用 AsyncTask 打造即時下載進度視窗

編輯:關於 Android 程式設計

AsyncTask 自 API level 3 起提供,因此幾乎所有仍在流通的 Android 版本都能使用。它是 Thread 之外的另一種選擇:Android 團隊鼓勵主執行緒(UI thread)專注於操作與畫面的流暢呈現,其餘工作(網路傳輸、檔案/磁碟/資料存取)最好都放到背景執行。Thread 通常還得搭配 Handler 使用,而 AsyncTask 的用意正是簡化背景執行緒程式碼的撰寫。

選擇的原則很簡單:如果預期工作能在幾秒內完成,用 AsyncTask 很合適;若執行時間很長,Android 強烈建議改用 Executor、ThreadPoolExecutor 與 FutureTask。

基本結構

使用 AsyncTask 必須建立一個繼承自它的子類,並傳入三個泛型參數:

  • Params:傳入 doInBackground() 的參數,數量不限。
  • Progress:doInBackground() 執行過程中回報給 UI thread 的中途資料,數量不限。
  • Result:最終執行結果。

若某項沒有資料要傳,填入 Void(注意 V 大寫)。

四個執行階段

  • onPreExecute():執行前的準備工作,例如在畫面上顯示進度表。
  • doInBackground():實際要跑的背景程式碼寫在這裡。
  • onProgressUpdate():用來更新目前的進度顯示。
  • onPostExecute():執行完畢,Result 會傳入這裡。

除了 doInBackground() 之外,其餘三個方法都在 UI thread 中被呼叫——這正是我們能直接操作控制項的原因。

實例:檔案下載與進度回饋

需求是「點擊按鈕開始下載 QQ Android 安裝包,並用一個對話框即時顯示下載進度」。進度條選用 GitHub 上可顯示百分比的 NumberProgressBar,觸發按鈕則用帶有動畫效果的 CircleButton。開源社群裡這類好用的控制項很多,後續再來研究它們的實作原理。

步驟 1:初始化進度對話框

 builder = new AlertDialog.Builder(MainActivity.this);
 LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
 mDialogView = inflater.inflate(R.layout.progress_dialog_layout, null);
 mNumberProgressBar = (NumberProgressBar) mDialogView.findViewById(R.id.number_progress_bar);
 builder.setView(mDialogView);
 mDialog = builder.create();

步驟 2:綁定按鈕事件

 findViewById(R.id.circle_btn).setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         dismissDialog();
         mNumberProgressBar.setProgress(0);
         myTask = new MyAsyncTask();
         myTask.execute(qqDownloadUrl);
     }
 });

步驟 3:實作 DownloadAsyncTask

 private class DownloadAsyncTask extends AsyncTask<String, Integer, String> {

     @Override
     protected void onPreExecute() {
         super.onPreExecute();
         mDialog.show();          // 開始前先彈出進度視窗
     }

     @Override
     protected void onPostExecute(String aVoid) {
         super.onPostExecute(aVoid);
         dismissDialog();
     }

     @Override
     protected void onProgressUpdate(Integer... values) {
         super.onProgressUpdate(values);
         mNumberProgressBar.setProgress(values[0]);
     }

     @Override
     protected void onCancelled(String aVoid) {
         super.onCancelled(aVoid);
         dismissDialog();
     }

     @Override
     protected void onCancelled() {
         super.onCancelled();
         dismissDialog();
     }

     @Override
     protected String doInBackground(String... params) {
         String urlStr = params[0];
         FileOutputStream output = null;
         try {
             URL url = new URL(urlStr);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();

             String qqApkFile = "qqApkFile";
             File file = new File(Environment.getExternalStorageDirectory() + "/" + qqApkFile);
             if (file.exists()) {
                 file.delete();
             }
             file.createNewFile();

             InputStream input = connection.getInputStream();
             output = new FileOutputStream(file);

             int total = connection.getContentLength();
             if (total <= 0) {
                 return null;     // 拿不到大小就算不出百分比
             }

             int plus = 0;
             int totalRead = 0;
             byte[] buffer = new byte[4 * 1024];
             while ((plus = input.read(buffer)) != -1) {
                 output.write(buffer);
                 totalRead += plus;
                 // 把百分比回報給 UI thread
                 publishProgress(totalRead * 100 / total);
                 if (isCancelled()) {
                     break;
                 }
             }
             output.flush();
         } catch (MalformedURLException e) {
             e.printStackTrace();
             if (output != null) {
                 try { output.close(); } catch (IOException e2) { e2.printStackTrace(); }
             }
         } catch (IOException e) {
             e.printStackTrace();
             if (output != null) {
                 try { output.close(); } catch (IOException e2) { e2.printStackTrace(); }
             }
         } finally {
             if (output != null) {
                 try { output.close(); } catch (IOException e) { e.printStackTrace(); }
             }
         }
         return null;
     }
 }

幾個關鍵點:publishProgress() 只能在 doInBackground() 中呼叫,它會把數值經由內部 Handler 送到 UI thread 的 onProgressUpdate();而迴圈中主動檢查 isCancelled(),是為了讓取消操作能即時生效——否則一個長時間下載即使被 cancel 也會拖到結束才停。

步驟 4:在 onPause 中處理取消(最容易被忽略的一步)

 @Override
 protected void onPause() {
     super.onPause();
     if (myTask != null && isFinishing()) {
         myTask.cancel(false);
     }
 }

這一步為什麼重要?假設 Activity 正在背景跑一個耗時任務,使用者按返回退出 Activity 甚至離開 App,背景任務不會自動停止。更糟的是,若 AsyncTask 內部持有 Activity 成員變數的參考,還會造成 Activity 的回收被延遲,形成一段時間的記憶體洩漏。

加上這段判斷後,Activity 退出時任務會一併取消,資源得以順利回收。這個步驟平時看不出效果,也不會有明顯症狀,但一旦出問題就很難排查——所以養成寫的習慣,比事後除錯划算得多。

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