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

網路圖片載入優化實戰:執行緒池 + 雙層緩存 + 按比例縮放

編輯:Android 開發實例

關於網路資源載入的文章不少,基本思路都是「執行緒 + 緩存」。本文在這個骨架上做了幾點優化:

  1. 採用執行緒池,避免為每張圖片建立一條執行緒。
  2. 記憶體緩存 + 檔案緩存雙層設計。
  3. 記憶體緩存嚴格限制在最大可用堆的 1/4,而不是單純依賴 SoftReference 讓 GC 決定。
  4. 解碼時按比例縮放,直接降低像素量以節省記憶體。

一、記憶體緩存 MemoryCache.java

public class MemoryCache {
    private static final String TAG = "MemoryCache";

    // 放入緩存時是同步操作。
    // LinkedHashMap 的最後一個參數 true 代表元素依最近使用次數由少到多排列(LRU),
    // 如此一來需要淘汰時,直接遍歷開頭即可拿到最久未使用的項目。
    private Map<String, Bitmap> cache = Collections
            .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));

    // 緩存中圖片所占用的位元組數,初始為 0
    private long size = 0;          // current allocated size
    private long limit = 1000000;   // max memory in bytes

    public MemoryCache() {
        // 使用可用堆的 25%
        setLimit(Runtime.getRuntime().maxMemory() / 4);
    }

    public void setLimit(long new_limit) {
        limit = new_limit;
        Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
    }

    public Bitmap get(String id) {
        try {
            if (!cache.containsKey(id)) {
                return null;
            }
            return cache.get(id);
        } catch (NullPointerException ex) {
            return null;
        }
    }

    public void put(String id, Bitmap bitmap) {
        try {
            if (cache.containsKey(id)) {
                size -= getSizeInBytes(cache.get(id));
            }
            cache.put(id, bitmap);
            size += getSizeInBytes(bitmap);
            checkSize();
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

    /**
     * 嚴格控制堆記憶體,超標時先淘汰最近最少使用的那張
     */
    private void checkSize() {
        Log.i(TAG, "cache size=" + size + " length=" + cache.size());
        if (size > limit) {
            Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Bitmap> entry = iter.next();
                size -= getSizeInBytes(entry.getValue());
                iter.remove();
                if (size <= limit) {
                    break;
                }
            }
            Log.i(TAG, "Clean cache. New size " + cache.size());
        }
    }

    public void clear() {
        cache.clear();
    }

    /** 圖片占用的記憶體 */
    long getSizeInBytes(Bitmap bitmap) {
        if (bitmap == null) {
            return 0;
        }
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

寫成 SoftReference 版本程式碼會短很多:

public class MemoryCache {

    private Map<String, SoftReference<Bitmap>> cache = Collections
            .synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());

    public Bitmap get(String id) {
        if (!cache.containsKey(id)) {
            return null;
        }
        SoftReference<Bitmap> ref = cache.get(id);
        return ref.get();
    }

    public void put(String id, Bitmap bitmap) {
        cache.put(id, new SoftReference<Bitmap>(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}

但我更推薦上面的 LRU 版本。差別在於 SoftReference 的回收時機由 GC 決定,你無法預期它何時被清掉,也可能在關鍵時刻突然全部失效;而自行計量 hit 的方式行為可預期,也便於除錯。

二、檔案緩存 FileCache.java

public class FileCache {
    private File cacheDir;

    public FileCache(Context context) {
        // 有 SD 卡就在 SD 卡建立 LazyList 目錄存放緩存檔案,
        // 沒有則退回系統的應用程式緩存目錄
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(
                    android.os.Environment.getExternalStorageDirectory(), "LazyList");
        } else {
            cacheDir = context.getCacheDir();
        }
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }

    public File getFile(String url) {
        // 以 url 的 hashCode 作為檔名
        String filename = String.valueOf(url.hashCode());
        // 另一種做法:String filename = URLEncoder.encode(url);
        return new File(cacheDir, filename);
    }

    public void clear() {
        File[] files = cacheDir.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            f.delete();
        }
    }
}

用 hashCode 當檔名的缺點是理論上存在碰撞風險,實務上若要更穩妥,可改用 URL 的 MD5 或 SHA-1 摘要。

三、核心:ImageLoader.java

public class ImageLoader {
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;

    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());

    // 執行緒池
    ExecutorService executorService;

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    // 進入 listview 時的預設佔位圖,可替換成自己的資源
    final int stub_id = R.drawable.stub;

    /** 最主要的對外方法 */
    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        // 先查記憶體緩存
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            // 沒有就開執行緒載入,並先顯示佔位圖
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);
        // 先查檔案緩存
        Bitmap b = decodeFile(f);
        if (b != null) {
            return b;
        }
        // 最後才從網路下載
        try {
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            CopyStream(is, os);
            os.close();
            return decodeFile(f);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // 解碼並按比例縮放以降低記憶體消耗;
    // 虛擬機對單張圖片的可配置記憶體也是有限制的
    private Bitmap decodeFile(File f) {
        try {
            // 先只讀取尺寸
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // 找出合適的縮放值,必須是 2 的次方
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // 帶著 inSampleSize 重新解碼
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    // 佇列中的工作項目
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            if (imageViewReused(photoToLoad)) {
                return;
            }
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad)) {
                return;
            }
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            // 更新 UI 必須回到 UI 執行緒
            Activity a = (Activity) photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    /**
     * 防止圖片錯位(ListView 回收再利用導致的張冠李戴)
     */
    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url)) {
            return true;
        }
        return false;
    }

    // 在 UI 執行緒中更新介面
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad)) {
                return;
            }
            if (bitmap != null) {
                photoToLoad.imageView.setImageBitmap(bitmap);
            } else {
                photoToLoad.imageView.setImageResource(stub_id);
            }
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

    public static void CopyStream(InputStream is, OutputStream os) {
        final int buffer_size = 1024;
        try {
            byte[] bytes = new byte[buffer_size];
            for (;;) {
                int count = is.read(bytes, 0, buffer_size);
                if (count == -1) {
                    break;
                }
                os.write(bytes, 0, count);
            }
        } catch (Exception ex) {
        }
    }
}

四、整體流程

先查記憶體緩存 → 命中則直接顯示;未命中則丟進執行緒池,先查檔案緩存 → 仍未命中才從網路下載並寫檔 → 解碼縮放 → 最後切回 UI 執行緒更新:

a.runOnUiThread(...);

使用方式很簡單:

ImageLoader imageLoader = new ImageLoader(context);
// ...
imageLoader.DisplayImage(url, imageView);

最典型的掛載點是 ListView 的 getView(),GridView 也同樣適用。

五、值得注意的細節

imageViewReused 為什麼必要。ListView 會回收並重複使用 item 檢視。若使用者快速滾動,A 位置的請求可能還在飛行中,此時那個 ImageView 已經被拿去顯示 B 的內容,直接 setImageBitmap 就會造成圖文不符。用 WeakHashMap 記錄「這個 ImageView 目前應該顯示哪個 url」,回來時比對一次即可攔下過期結果。

兩次解碼的技巧。inJustDecodeBounds = true 讓 BitmapFactory 只讀取檔案標頭取得尺寸而不真正配置像素記憶體,算出 inSampleSize 後再正式解碼。這是控制 OOM 最有效的單一手段。

連線一定要關閉。範例中 HttpURLConnection 沒有 disconnect,實作時應補上並改用 try-with-resources 管理串流。

最後要補充的是時代背景:這套自行打造的分層緩存,正是今日 Glide、Fresco、Picasso 等函式庫在做的事,而且它們處理得更完整——包含請求取消、生命週期綁定、多種快取政策、進度回報與資源 reuse。新專案沒有必要重造這個輪子;理解本文的原理,是為了在函式庫行為不如預期時知道該往哪裡查。

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