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

Android AsyncTask 用法整理:異步載入網路圖片實作

編輯:關於 Android 程式設計

Android 中實作異步機制主要有兩條路:Thread 搭配 Handler,以及 AsyncTask。本文記錄 AsyncTask 的學習過程,以備日後查閱。

一、三個泛型參數

AsyncTask<Params, Progress, Result> 是一個抽象類別,通常作為父類被繼承。繼承時必須指定三個泛型參數:

  • Params:啟動任務時傳入參數的型別
  • Progress:後台任務執行過程中所回報進度的型別
  • Result:後台任務完成後回傳結果的型別

二、需要覆寫的四個方法

一個異步任務的生命週期通常由這四個方法串起來:

  • onPreExecute():在背景作業開始前於 UI 執行緒執行,通常用來做介面初始化,例如顯示進度條。
  • doInBackground(Params...):onPreExecute 之後立刻執行,在背景執行緒中進行耗時運算。此方法中可呼叫 publishProgress(Progress...) 回報進度。
  • onProgressUpdate(Progress...):當 doInBackground 呼叫 publishProgress 時觸發,在 UI 執行緒中執行,用來更新進度元件。
  • onPostExecute(Result):背景任務完成後呼叫,接收 doInBackground 的回傳值,在 UI 執行緒中更新介面。

關鍵設計在於:只有 doInBackground 跑在背景執行緒,其餘三個都在 UI 執行緒。這正是 AsyncTask 的價值——它把執行緒切換的細節封裝起來,開發者只需覆寫方法即可。

三、使用規則

官方文件列出幾條硬性約束:

Threading rules

There are a few threading rules that must be followed for this class to work properly:

1. The AsyncTask class must be loaded on the UI thread.
   This is done automatically as of JELLY_BEAN.
2. The task instance must be created on the UI thread.
3. execute(Params...) must be invoked on the UI thread.
4. Do not call onPreExecute(), onPostExecute(Result),
   doInBackground(Params...), onProgressUpdate(Progress...) manually.
5. The task can be executed only once
   (an exception will be thrown if a second execution is attempted).

翻譯成實務語言就是:

  • AsyncTask 的類別必須在 UI 執行緒中載入(JELLY_BEAN 之後已自動處理)
  • AsyncTask 的實例必須在 UI 執行緒中建立
  • execute() 必須在 UI 執行緒中呼叫
  • 不要手動呼叫那四個回呼方法,它們由框架自行觸發
  • 同一個 AsyncTask 實例只能執行一次,重複執行會拋出例外

四、實作範例:異步載入網路圖片

先來看成果。這個 demo 的重點是點擊後異步下載一張網路圖片,並在過程中顯示進度百分比,涵蓋了 I/O 操作與網路請求等知識點。

圖一:首頁,點擊按鈕進入載入頁面
圖二:載入過程中顯示的進度百分比
圖三:進度達 100% 後顯示完整圖片

布局檔

主介面就是一個按鈕加上頁面跳轉。載入頁的布局用 RelativeLayout 疊放三個元件:ImageView 顯示圖片、ProgressBar 顯示進度、TextView 顯示百分比。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone" />

    <TextView
        android:id="@+id/mTextprogress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="15%"
        android:textSize="13sp" />
</RelativeLayout>

ImageTest.java

package com.example.asynctaskdemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 異步載入並顯示一張網路圖片
 */
public class ImageTest extends Activity {

    private String TAG = ImageTest.class.getSimpleName();

    private ImageView mImageView;
    private ProgressBar mProgressBar;
    private TextView mTextProgress;
    private MyAsyncTaskShowImg mTask;

    private static String mImgUrl = "https://h.hiphotos.baidu.com/image/pic/item/"
            + "9922720e0cf3d7ca14dcc750f71fbe096b63a9ea.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image);
        initView();
        mTask = new MyAsyncTaskShowImg();
        mTask.execute(mImgUrl);
    }

    private void initView() {
        mTextProgress = (TextView) findViewById(R.id.mTextprogress);
        mImageView = (ImageView) findViewById(R.id.imageView1);
        mProgressBar = (ProgressBar) findViewById(R.id.progress);
    }

    class MyAsyncTaskShowImg extends AsyncTask<String, Integer, Bitmap> {

        /** 初始化 UI 元件 */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressBar.setVisibility(View.VISIBLE);
            mTextProgress.setText("0%");
        }

        /** 執行耗時的背景作業 */
        @Override
        protected Bitmap doInBackground(String... params) {
            String mImgUrl = params[0];
            String mFileName = "temp_pic";
            Log.d(TAG, "mImgUrl is " + mImgUrl);

            Bitmap mBitmap = null;
            InputStream is = null;
            OutputStream out = null;
            HttpURLConnection connection = null;

            try {
                connection = (HttpURLConnection) new URL(mImgUrl).openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(false);
                connection.setConnectTimeout(10 * 1000);

                is = connection.getInputStream();
                out = openFileOutput(mFileName, MODE_PRIVATE);

                byte[] data = new byte[1024];
                int seg = 0;
                long totalSize = connection.getContentLength();
                Log.d(TAG, "total size is " + totalSize);

                long current = 0;
                while (!isCancelled() && (seg = is.read(data)) != -1) {
                    current += seg;
                    Log.d(TAG, "current size is " + current);

                    int progress = (int) ((float) current / totalSize * 100);
                    Log.d(TAG, "progress size is " + progress);

                    // 回報進度,會觸發 onProgressUpdate
                    publishProgress(progress);
                    out.write(data, 0, seg);
                }

                mBitmap = BitmapFactory.decodeFile(
                        getFileStreamPath(mFileName).getAbsolutePath());
                Log.d(TAG, "file is " + getFileStreamPath(mFileName).getAbsolutePath());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 收尾工作放在 finally 中,確保連線與串流一定被關閉
                if (out != null) {
                    try { out.close(); } catch (IOException e) { }
                }
                if (is != null) {
                    try { is.close(); } catch (IOException e) { }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return mBitmap;
        }

        /** 更新載入進度 */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mTextProgress.setText(values[0] + "%");
        }

        /** 把 doInBackground 的結果回傳到 UI 執行緒 */
        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            mProgressBar.setVisibility(View.GONE);
            mTextProgress.setVisibility(View.GONE);
            mImageView.setImageBitmap(result);
            Toast.makeText(ImageTest.this, "圖片加載完成。", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
            // cancel() 只是把狀態標記為 cancelled,並不會真的中止背景執行緒
            mTask.cancel(true);
        }
    }
}

幾個實作要點

先存檔再解碼。這裡沒有直接把串流轉成 Bitmap,而是先寫入內部檔案,再用 BitmapFactory.decodeFile() 讀回。這樣做的好處是記憶體峰值較低,也讓圖片有了本地快取,第二次進入頁面不必重新下載。

進度計算要防溢位與除零。(int) ((float) current / totalSize * 100) 先轉 float 再運算,避免大數相乘溢位;若伺服器未回傳 Content-Length,totalSize 會是 -1,此時除法結果沒有意義,應另外處理這種情況。

cancel() 不是真的中止。呼叫 cancel(true) 只是把任務狀態改為 cancelled,正在進行的 I/O 不會立刻停下。因此迴圈中要主動檢查 isCancelled() 才有意義,範例已加上這個判斷。

資源釋放要放 finally。原始範例把 close 寫在 try 區塊末尾,一旦中途拋出例外就會跳過,造成串流洩漏。上面已改寫為 finally 區塊。

AsyncTask 已被標記為 deprecated。從 API 30 起 AsyncTask 不再建議使用。新專案若要處理網路請求,建議改用 Kotlin 協程、Retrofit、OkHttp 搭配 LiveData/Flow,或 WorkManager(適合需要保證完成或由系統代管的背景工作)。若只是單純載入圖片,直接使用 Glide、Picasso、Coil 這類成熟框架會省下大量功夫。

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