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

非同步載圖第二彈:修掉崩潰、補上進度,並換用 NumberProgressBar

編輯:關於 Android 程式設計

上一節我們用 AsyncTask 完成了非同步下載圖片,但留下了三個問題:無網路時點擊會崩潰、進度條沒有真的更新、以及只能用系統內建的 ProgressBar。這次逐一解決。

問題一:為什麼沒網路就會當

回頭看那段落下的程式碼:

try {
    HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
    connection.setDoInput(true);
    connection.connect();
    inputStream = connection.getInputStream();
    downloadImg = BitmapFactory.decodeStream(inputStream);
}

原因很明顯:沒有網路就拿不到串流。由於我們沒做圖片快取,每次點擊都會重新連線,一旦連線失敗 inputStream 就是 null,把 null 丟給 decodeStream 自然炸掉。

所以第一層防護是判斷串流是否為 null。但更好的做法是「一開始就不要讓使用者點」。

先試 WifiManager,發現不夠用

WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE);
int wifiState = manager.getWifiState();   // wifi 狀態

狀態常數如下:

WIFI_STATE_DISABLING = 0;  // 停用中
WIFI_STATE_DISABLED  = 1;  // 不可用
WIFI_STATE_ENABLING  = 2;  // 啟動中
WIFI_STATE_ENABLED   = 3;  // 已就緒
WIFI_STATE_UNKNOWN   = 4;  // 未知

看起來很像路由器啟動的過程,但仔細想就會發現:WIFI_STATE_ENABLED 只代表「無線網路已開啟」,並不代表「連上網路」,更不代表「能連上網際網路」。用它來判斷網路可用性會誤判。

另外別忘了權限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

改用 ConnectivityManager

ConnectivityManager cManager =
        (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mInfo = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean available = mInfo.isAvailable();

這個 API 才是真正回答「網路是否可用」的問題。

把判斷組合起來

但只判斷網路還不夠——URL 為空的一樣會炸。考慮到健壯性,兩個條件都要 AND,並據此決定按鈕是否可點。

Button downBtn = (Button) findViewById(R.id.downBtn);
if (mInfo.isAvailable() && !TextUtils.isEmpty(url)) {
    downBtn.setClickable(true);
    downBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new ImageDownloadTask(MainActivity.this, img, bar).execute(url);
        }
    });
} else {
    downBtn.setClickable(false);
    downBtn.setOnClickListener(null);
    Toast.makeText(MainActivity.this, "當前無網路", Toast.LENGTH_SHORT).show();
}

補充一句:在正式專案裡,判斷網路狀態通常不會寫在 Activity 裡,而是註冊一個網路狀態變化的廣播接收器統一處理。這部分留待談廣播時再說。

問題二:進度為什麼不動

要做進度條,需要三樣東西:總長度、當前長度、以及一個通知刷新的方法。關鍵程式碼:

int totalLength;              // 總長度
URL imageUrl = new URL(params[0]);
int length = -1;
InputStream inputStream = null;

HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
totalLength = connection.getContentLength();   // 關鍵:取得總大小

if (inputStream != null) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int count = 0;
    while ((length = inputStream.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
        count += length;
        // 通知 onProgressUpdate 更新進度
        publishProgress((int) ((count / (float) totalLength) * 100));
    }
    byte[] data = baos.toByteArray();
    downloadImg = BitmapFactory.decodeByteArray(data, 0, data.length);
    return "ok";
}

然後在 UI 端接收:

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

注意 totalLength 若為 -1(伺服器未帶 Content-Length,例如 chunked 編碼),進度計算會變成負數或異常,實務上要加一層判斷退回「不確定進度」模式。

問題三:換上 NumberProgressBar

daimajia 的 NumberProgressBar 是一個把數字直接畫在條上的開源元件,視覺比系統 ProgressBar 好得多。專案在 github.com/daimajia/NumberProgressBar,Eclipse 與 Android Studio 的匯入方式都有說明。

版面配置:

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

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/downBtn"
        android:layout_below="@id/hello"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="down"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <ImageView
        android:id="@+id/img"
        android:layout_below="@id/downBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:visibility="gone" />

    <com.daimajia.numberprogressbar.NumberProgressBar
        android:id="@+id/bar"
        android:layout_below="@id/downBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />
</RelativeLayout>

與其把一堆屬性寫在標籤上,用 style 集中管理更清爽:

<style name="NumberProgressBar_Funny_Orange">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">match_parent</item>
    <item name="max">100</item>
    <item name="progress">0</item>
    <item name="progress_unreached_color">#CCCCCC</item>
    <item name="progress_reached_color">#FF530D</item>
    <item name="progress_text_size">10sp</item>
    <item name="progress_text_color">#FF530D</item>
    <item name="progress_reached_bar_height">1.5dp</item>
    <item name="progress_unreached_bar_height">0.75dp</item>
</style>

這個 style 涵蓋了寬高、最大值、進度、顏色、字級等常用屬性,之後套用 style="@style/NumberProgressBar_Funny_Orange" 即可。若匯入後找不到 style,手動把它的 attrs 資源複製進來也能解決。

AsyncTask 主體

public class ImageDownloadTask extends AsyncTask<String, Integer, String> {

    private Bitmap downloadImg;
    private NumberProgressBar mBar;
    private Context mContext;
    private ImageView netImageView;

    public ImageDownloadTask(Context context, ImageView imageView, NumberProgressBar bar) {
        this.mContext = context;
        this.netImageView = imageView;
        this.mBar = bar;
    }

    @Override
    protected void onPreExecute() {
        mBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        int totalLength;
        InputStream inputStream = null;
        try {
            URL imageUrl = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
            connection.setDoInput(true);
            connection.connect();
            inputStream = connection.getInputStream();
            totalLength = connection.getContentLength();

            if (inputStream != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int count = 0;
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                    count += length;
                    publishProgress((int) ((count / (float) totalLength) * 100));
                }
                byte[] data = baos.toByteArray();
                downloadImg = BitmapFactory.decodeByteArray(data, 0, data.length);
                return "ok";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

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

    @Override
    protected void onPostExecute(String result) {
        mBar.setVisibility(View.GONE);
        netImageView.setVisibility(View.VISIBLE);
        netImageView.setImageBitmap(downloadImg);
        Toast.makeText(mContext, "加載完畢", Toast.LENGTH_LONG).show();
    }
}

執行看看:

三個問題都解決了,但還有三個新問題

值得誠實指出的是,這份程式碼仍有幾處會在真實環境出狀況:totalLength 為 -1 時進度計算失效;onPostExecute 未檢查 downloadImg 是否為 null,載入失敗會直接 NPE;以及 ConnectivityManager.getNetworkInfo() 在 Android 10(API 29)已被標記為 deprecated,判斷網路狀態現在推薦用 NetworkCapabilities。

另外,NetworkOnMainThread 之外,圖片下載建議加上磁碟快取(如 Glide、Picasso 已內建),否則每次進入頁面都要重新下載。下次再來談動態設定 progress 的樣式,以及自己動手做一個 progressbar。

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