Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 下載網絡圖片的兩種可靠方案

編輯:Android 開發實例

在加載網絡圖片時,如果網絡較慢,往往會出現下載不成功的問題。經過一番排查與搜索,這裡總結出兩種更為可靠的方案。

常見寫法及其局限

通常我們會用這樣的代碼:

// 獲取 connection,方法略
conn = getURLConnection(url);
is = conn.getInputStream();

// 獲取 Bitmap 的引用
Bitmap bitmap = BitmapFactory.decodeStream(is);

問題就在於:網絡狀況不佳時,這種「邊讀邊解碼」的方式很可能拿不到完整數據,導致圖片加載失敗。

推薦方案:先完整下載再解碼

更穩妥的做法是先把圖片數據全部讀入內存,再進行解碼:

// 獲取長度
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);
}

這樣做的好處是:即使網速不佳,也能確保把圖片數據完整下載下來,再解碼生成 Bitmap 對象,從而有針對性地保證「只要圖片存在就能下載成功」。當然,讀取時也可以採用 java.nio.ByteBuffer,這樣便無需事先知道數據長度,既規避了 http 返回 length 偶爾不準確的問題,也省去了數組拷貝的開銷。

封裝成通用方法

把上述思路封裝一下,便得到一個健壯的圖片加載方法:

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

    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) {
        bitmap = BitmapFactory.decodeResource(c.getResources(),
                com.jixuzou.moko.R.drawable.defaultimg);
        return bitmap;
    }
    return bitmap;
}

這段代碼還貼心地加入了異常兜底——一旦下載失敗,便回退顯示一張默認圖片,避免界面出現空白,用戶體驗更為友好。

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