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

網路圖片老是下載失敗?改用「先收完再解碼」的做法

編輯:關於 Android 開發

下載網路圖片時,如果網路狀況不穩,很容易出現圖片出不來的情況。問題往往不在你的邏輯,而在於直覺寫法本身有缺陷。

常見但有問題的寫法

// 取得 connection(細節省略)
conn = getURLConnection(url);
is = conn.getInputStream();

// 直接從串流解碼
Bitmap bitmap = BitmapFactory.decodeStream(is);

decodeStream() 會邊讀邊解,一旦連線在中途斷掉或速度過慢,讀到的位元組不足,解碼就直接失敗,回傳 null。使用者看到的就是一片空白。

改良做法:先把資料收齊,再解碼

int length = (int) conn.getContentLength();
if (length != -1) {
    byte[] imgData = new byte[length];
    byte[] temp = new byte[512];
    int readLen = 0;
    int destPos = 0;

    while ((readLen = is.read(temp)) > 0) {
        System.arraycopy(temp, 0, imgData, destPos, readLen);
        destPos += readLen;
    }

    bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
}

這樣做的好處很明確:網路再慢,只要連線沒斷,迴圈就會持續把資料收滿,收完才交給解碼器。只要圖片真的存在,就下載得下來。

更省事的做法:用 ByteBuffer

上面這段程式碼有個前提——得先知道長度。但 Content-Length 並非總是可靠(chunked 編碼時甚至回傳 -1)。若改用 java.nio.ByteBuffer,就不必事先知道大小,也省掉自己搬移陣列的動作:

ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] temp = new byte[512];
int readLen;
while ((readLen = is.read(temp)) > 0) {
    if (buffer.remaining() < readLen) {
        ByteBuffer bigger = ByteBuffer.allocate(buffer.capacity() * 2);
        bigger.put(buffer.array(), 0, buffer.position());
        buffer = bigger;
    }
    buffer.put(temp, 0, readLen);
}
bitmap = BitmapFactory.decodeByteArray(buffer.array(), 0, buffer.position());

完整範例(含錯誤回退)

public synchronized Bitmap getBitMap(Context c, String url) {
    URL myFileUrl = null;
    Bitmap bitmap = null;
    try {
        myFileUrl = new URL(url);
    } catch (MalformedURLException e) {
        return BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultimg);
    }

    try {
        HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        int length = (int) conn.getContentLength();
        if (length != -1) {
            byte[] imgData = new byte[length];
            byte[] temp = new byte[512];
            int readLen = 0;
            int destPos = 0;
            while ((readLen = is.read(temp)) > 0) {
                System.arraycopy(temp, 0, imgData, destPos, readLen);
                destPos += readLen;
            }
            bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
        }
    } catch (IOException e) {
        return BitmapFactory.decodeResource(c.getResources(), R.drawable.defaultimg);
    }
    return bitmap;
}

三個別忘了的現代化補充

第一,這個方法用了 synchronized,代表所有呼叫被序列化,下載多張圖會互相排隊;實務上應把網路移到背景執行緒,並移除方法級別的鎖。

第二,網路請求一定要設連線與讀取逾時(setConnectTimeout/setReadTimeout),否則卡住的連線會佔著執行緒不放。

第三,認真做的話不必自己造輪子:Glide 或 Coil 已經處理好重試、逾時、磁碟快取、記憶體快取與生命週期綁定,還能自動避免列表捲動時的圖片錯位。上面這些原理值得懂,但產品程式碼請用成熟函式庫。

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