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

遠端圖片怎麼載入才不卡?Android 異步下載與多層快取實作

編輯:關於 Android 程式設計

對「用戶端—伺服器端」架構的應用來說,從遠端抓圖是家常便飯。但圖片是流量與記憶體的雙重大戶,處理不好會有兩個後果:使用者的行動流量莫名其妙被吃光,以及列表滑動時的嚴重卡頓。一旦使用者發現是你把你的流量燒掉,這個 App 的下場可想而知。

所以答案只有兩件事:異步下載與本機快取。

一、為什麼必須異步

Android 的主執行緒若 5 秒內沒有回應就會拋出 ANR。抓取遠端大資源時這個門檻非常容易踩到。有兩種標準解法:

1. 開啟新執行緒下載,完成後透過 Handler 機制送訊息回主執行緒更新 UI。
2. 直接使用 Android 提供的 AsyncTask。

具體用法查 API 即可,這裡把重點放在快取。

二、為什麼必須快取

不可能每次都重新下載(例如 ListView 滑動時),那是浪費流量;但也不能把所有圖片都塞進記憶體,圖片太佔空間,直接走向 OOM。常見的兩條路:

路線 A:存到 SD 卡,搭配 LRU 等淘汰策略,讓佔用量維持在可控範圍。
路線 B:全部放記憶體,設定過期時間與 LRU 規則。

成熟的做法通常是兩者並用,形成多層快取。

三、SD 卡快取實作

先在 SD 卡上劃出一塊空間。開闢前必須先確認剩餘空間夠用(例如需要 10MB)。取圖時流程是:先在本機目錄找,找到就使用並更新最後使用時間;找不到才透過 URL 下載,成功後存入並使用,失敗則重試(例如三次)。存入前再檢查配額是否用滿,不夠就依 LRU 刪掉最久沒被使用的檔案。

存檔:

private void saveBmpToSd(Bitmap bm, String url) {
    if (bm == null) {
        Log.w(TAG, "trying to save null bitmap");
        return;
    }
    // 判斷 sdcard 上的空間
    if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
        Log.w(TAG, "Low free space on sd, do not cache");
        return;
    }
    String filename = convertUrlToFileName(url);
    String dir = getDirectory(filename);
    File file = new File(dir + "/" + filename);
    try {
        file.createNewFile();
        OutputStream outStream = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();
        Log.i(TAG, "Image saved to sd");
    } catch (FileNotFoundException e) {
        Log.w(TAG, "FileNotFoundException");
    } catch (IOException e) {
        Log.w(TAG, "IOException");
    }
}

計算剩餘空間:

/**
 * 計算 sdcard 上的剩余空間
 */
private int freeSpaceOnSd() {
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat.getBlockSize()) / MB;
    return (int) sdFreeMB;
}

更新最後使用時間:LRU 的基礎就是這個時間戳。

/**
 * 修改文件的最後修改時間
 */
private void updateFileTime(String dir, String fileName) {
    File file = new File(dir, fileName);
    long newModifiedTime = System.currentTimeMillis();
    file.setLastModified(newModifiedTime);
}

快取清理:當總量大於設定上限,或 SD 卡剩餘空間不足時,刪掉最近沒被使用的四成檔案。

/**
 * 計算存儲目錄下的文件大小。當總大小超過 CACHE_SIZE,
 * 或 sdcard 剩餘空間低於 FREE_SD_SPACE_NEEDED_TO_CACHE 時,
 * 刪除 40% 最近沒有被使用的文件
 */
private void removeCache(String dirPath) {
    File dir = new File(dirPath);
    File[] files = dir.listFiles();
    if (files == null) {
        return;
    }
    int dirSize = 0;
    for (int i = 0; i < files.length; i++) {
        if (files[i].getName().contains(WHOLESALE_CONV)) {
            dirSize += files[i].length();
        }
    }
    if (dirSize > CACHE_SIZE * MB || FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
        int removeFactor = (int) ((0.4 * files.length) + 1);
        Arrays.sort(files, new FileLastModifSort());
        Log.i(TAG, "Clear some expired cache files");
        for (int i = 0; i < removeFactor; i++) {
            if (files[i].getName().contains(WHOLESALE_CONV)) {
                files[i].delete();
            }
        }
    }
}

/**
 * 刪除過期文件
 */
private void removeExpiredCache(String dirPath, String filename) {
    File file = new File(dirPath, filename);
    if (System.currentTimeMillis() - file.lastModified() > mTimeDiff) {
        Log.i(TAG, "Clear some expired cache files");
        file.delete();
    }
}

依修改時間排序:

/**
 * 根據文件的最後修改時間進行排序
 */
class FileLastModifSort implements Comparator<File> {
    public int compare(File arg0, File arg1) {
        if (arg0.lastModified() > arg1.lastModified()) {
            return 1;
        } else if (arg0.lastModified() == arg1.lastModified()) {
            return 0;
        } else {
            return -1;
        }
    }
}

四、記憶體快取:雙層設計

記憶體有限,不能無腦往裡塞。一個實用的手法是分成兩層:常用的放 A 快取,不常用的放 B 快取。取資料時先問 A,A 沒有再問 B;B 裡裝的是被 A 依 LRU 擠出來的項目。回收壓力集中在 B,A 的命中率就能維持得比較高。

A 快取:

private final HashMap<String, Bitmap> mHardBitmapCache =
        new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY / 2, 0.75f, true) {
    @Override
    protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
        if (size() > HARD_CACHE_CAPACITY) {
            // 當 size 大於 30 時,把最近不常用的 key 放到 mSoftBitmapCache,
            // 從而保證 mHardBitmapCache 的效率
            mSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue()));
            return true;
        } else {
            return false;
        }
    }
};

B 快取:

/**
 * 當 mHardBitmapCache 的 key 超過 30 個時,
 * 會依 LRU 把最近沒被使用的 key 放進這裡。
 * Bitmap 使用 SoftReference,記憶體不足時會被垃圾回收
 */
private final static ConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache =
        new ConcurrentHashMap<String, SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2);

快取查詢:

/**
 * 從快取中獲取圖片
 */
private Bitmap getBitmapFromCache(String url) {
    // 先從 mHardBitmapCache 中獲取
    synchronized (mHardBitmapCache) {
        final Bitmap bitmap = mHardBitmapCache.get(url);
        if (bitmap != null) {
            // 找到後移到 linkedhashmap 最前面,確保在 LRU 中最後才被刪除
            mHardBitmapCache.remove(url);
            mHardBitmapCache.put(url, bitmap);
            return bitmap;
        }
    }

    // mHardBitmapCache 找不到,改找 mSoftBitmapCache
    SoftReference<Bitmap> bitmapReference = mSoftBitmapCache.get(url);
    if (bitmapReference != null) {
        final Bitmap bitmap = bitmapReference.get();
        if (bitmap != null) {
            return bitmap;
        } else {
            mSoftBitmapCache.remove(url);
        }
    }
    return null;
}

都沒有就下載:

/**
 * 異步下載圖片
 */
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

    private static final int IO_BUFFER_SIZE = 4 * 1024;
    private String url;
    private final WeakReference<ImageView> imageViewReference;

    public ImageDownloaderTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        url = params[0];
        final HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(TAG, "從" + url + "中下載圖片時出錯!,錯誤碼:" + statusCode);
                return null;
            }
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = entity.getContent();
                    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                    outputStream = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
                    copy(inputStream, outputStream);
                    outputStream.flush();
                    final byte[] data = dataStream.toByteArray();
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (IOException e) {
            getRequest.abort();
            Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
        } catch (IllegalStateException e) {
            getRequest.abort();
            Log.w(TAG, "Incorrect URL:" + url);
        } catch (Exception e) {
            getRequest.abort();
            Log.w(TAG, "Error while retrieving bitmap from " + url, e);
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return null;
    }
}

用 WeakReference 包住 ImageView 是為了避免下載途中 Activity 被回收卻仍被持有;每個 ImageView 也應該掛上 tag,回來時比對 URL 是否還是最新的,否則快速捲動清單會出現「圖片錯位」的經典 bug。

以上是兩條主要路線。有些應用會在下載時加上執行緒池與訊息佇列,讓批量抓圖的效率再好一些,有興趣可以再深入。

總結一句:遠端圖片這類較大的資源,一定要在異步執行緒中取得,並建立本機快取層。

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