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

Android AsyncTask 異步任務詳解與實戰

編輯:Android 程式設計入門

由於 Android 的 UI 線程並非線程安全,若在 UI 線程中執行耗時任務,很容易導致程序崩潰;而且目前網絡任務也不允許在 UI 線程中執行。除了直接寫線程之外,Android 還提供了 AsyncTask(異步任務類),能更簡便地處理耗時任務。

AsyncTask 的三個泛型參數

AsyncTask<> 是一個抽象類,通常用於繼承,繼承時需指定三個泛型參數:

  1. Params:啟動任務時傳入參數的類型,是一個數組,可傳多個,通過 params[0]、params[1] 獲取。
  2. Progress:後台任務完成進度的類型。
  3. Result:後台任務執行完畢返回結果的類型。

使用步驟

  1. 繼承抽象類,實現子類並傳入三個泛型參數,不需要的可設為 Void。
  2. 按需實現以下方法:
    • doInBackground(Params...):必須實現,寫後台線程要執行的任務,在子線程運行(其他方法都在 UI 線程執行),可調用 publishProgress() 更新進度。
    • onProgressUpdate(Progress...):調用 publishProgress 時觸發。
    • onPreExecute():在 doInBackground 前執行,用於準備工作。
    • onPostExecute(Result):doInBackground 結束後自動調用,返回值會傳入,可在這裡處理結果。
  3. new 出子類實例後,調用 execute(Params...)。

注意:對象必須在 UI 線程中創建、execute 必須在 UI 線程中調用、上述方法均由系統自動調用、每個對象只能執行一次,多次調用會引發異常。

實例一:下載並顯示圖片

點擊按鈕後在後台下載圖片,下載完畢在 onPostExecute 中顯示。僅用了兩個函數:

public class MainActivity extends Activity {
    Button bn;
    ImageView iv;
    String url = "/hvtimg/bjafjc/3xglb9xf.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bn = (Button) findViewById(R.id.down);
        iv = (ImageView) findViewById(R.id.image);
        bn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AsyncDownload().execute(url);
            }
        });
    }

    class AsyncDownload extends AsyncTask<String, Integer, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                InputStream is = url.openStream();
                BitmapFactory.Options op = new BitmapFactory.Options();
                op.inSampleSize = 2;
                return BitmapFactory.decodeStream(is, null, op);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            iv.setImageBitmap(result);
        }
    }
}

實例二:帶進度條的下載

點擊下載後,先獲取文件大小並設置 progressBar 最大值,然後邊下載、邊存本地、邊更新進度,完成後從本地讀取圖片顯示。這裡多用了 onProgressUpdate:

class AsyncDownload extends AsyncTask<String, Integer, Void> {
    @Override
    protected Void doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            fileSize = conn.getContentLength();
            publishProgress(0x111);
            FileOutputStream fos = new FileOutputStream(getPath());
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
                downloadSize += len;
                publishProgress(0x222);
            }
            publishProgress(0x333);
            is.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        switch (values[0]) {
            case 0x111:
                progressBar.setMax(fileSize);
                break;
            case 0x222:
                progressBar.setProgress(downloadSize);
                break;
            case 0x333:
                try {
                    if (getPath().endsWith(".jpg") || getPath().endsWith(".png")) {
                        FileInputStream fis = new FileInputStream(getPath());
                        iv.setImageBitmap(BitmapFactory.decodeStream(fis));
                    }
                    downloadSize = 0;
                    fileSize = 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}

用 Handler 實現同樣的功能

onProgressUpdate 這個函數,平時我們在線程裡通常用 Handler 來實現。其實能用 AsyncTask 實現的,直接用線程 + Handler 也完全可行。下面是用 Handler 實現的版本:

Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case 0x111:
                progressBar.setMax(fileSize);
                break;
            case 0x222:
                progressBar.setProgress(downloadSize);
                break;
            case 0x333:
                try {
                    if (getPath().endsWith(".jpg") || getPath().endsWith(".png")) {
                        FileInputStream fis = new FileInputStream(getPath());
                        iv.setImageBitmap(BitmapFactory.decodeStream(fis));
                    }
                    downloadSize = 0;
                    fileSize = 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
};

class AsyncDownload extends AsyncTask<String, Integer, Void> {
    @Override
    protected Void doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            fileSize = conn.getContentLength();
            handler.sendEmptyMessage(0x111);
            FileOutputStream fos = new FileOutputStream(getPath());
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
                downloadSize += len;
                handler.sendEmptyMessage(0x222);
            }
            handler.sendEmptyMessage(0x333);
            is.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

AsyncTask 把平常使用線程進行異步操作的各種要素打包在一起,確實省了不少事。掌握它,異步處理會變得更加從容。

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