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

Android 檔案下載實作(三):用 AsyncTask 打造非同步下載體驗

編輯:關於 Android 程式設計

網路請求絕對不能寫在主執行緒上,否則畫面會整個卡住。本篇就用 AsyncTask 把下載動作丟到背景執行緒,同時在前景掛上一個等待提示。

下載頁面的完整實作

public class downloadActivity extends Activity {
    private TextView myTextView = null;
    private Button button = null;
    private static final String path = "https://192.168.0.179:8080/Myweb/download.do";
    private ProgressDialog progressDialog = null;
    private URL url = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download);

        // 取出註冊頁面用 Intent 帶過來的使用者名稱
        Intent intent = getIntent();
        String value = intent.getStringExtra("username");
        value = "hello" + " " + value;
        myTextView = (TextView) findViewById(R.id.textView1);
        myTextView.setText(value);

        button = (Button) this.findViewById(R.id.download_btn);

        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("請耐心等待,檔案正在下載中....");

        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                new DownloadFilesTask().execute(url);
            }
        });
    }

    private class DownloadFilesTask extends AsyncTask<URL, Void, Void> {
        @Override
        protected void onPreExecute() {
            progressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(URL... urls) {
            httpUtils.sendDownloadPost(urls[0]);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            progressDialog.dismiss();
            super.onPostExecute(result);
        }
    }
}

AsyncTask 的三個泛型參數

宣告 AsyncTask 時需要指定三個型別,各自代表不同階段所使用的資料:

  1. Params:execute() 時傳入的參數型別。本文傳的是 URL。
  2. Progress:背景運算期間對外發布的進度單位,通常搭配進度條使用。
  3. Result:背景運算結束後回傳的結果型別。

本文沒有做進度條,只用了 ProgressDialog 顯示等待提示,因此第二個參數留空;而檔案已經在 httpUtils 中直接寫入 SD 卡,不需要回傳結果,所以第三個參數也留空。

可以覆寫的四個方法

  1. onPreExecute():任務被觸發後,立刻在 UI 執行緒上執行。通常用來做前置準備,例如顯示進度條。
  2. doInBackground(Params...):在背景執行緒上執行,緊接著 onPreExecute() 之後。耗時運算都放在這裡,計算結果會被回傳到最後一個步驟;過程中也能呼叫 publishProgress() 對外發布進度。
  3. onProgressUpdate(Progress...):在 UI 執行緒上被呼叫,用來更新進度條、顯示日誌等,讓使用者知道背景工作仍在進行。
  4. onPostExecute(Result):背景運算結束後在 UI 執行緒上執行,doInBackground 的回傳值會作為參數傳入,通常用來更新介面。

把耗時的網路下載交給 AsyncTask,主執行緒就能保持順暢,使用者的等待過程也有明確回饋。

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