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

Android 網路圖片載入優化實戰:線程池、雙層快取與按比例縮圖

編輯:關於 Android 程式設計

網路圖片載入這個主題網上文章不少,核心思路歸結起來就是「執行緒 + 快取」。但如果只停在這八個字,實作時還是會遇到記憶體爆掉、清單圖片錯位、二次捲動重新下載等實際問題。本文把可落地的優化拆成四個要點,並給出完整的類別結構。

四個優化切入點

  1. 使用線程池:以固定數量的工作執行緒取代「一張圖一條 Thread」。
  2. 雙層快取:記憶體快取負責速度,檔案快取負責跨啟動存活。
  3. 嚴格限制記憶體上限:網上常見做法是 SoftReference 依賴 GC 回收,但回收時機不可控;本文示範用可用堆的 1/4 作為硬性上限,並以 LRU 策略淘汰。
  4. 下載後按比例縮圖:降低單張 Bitmap 佔用的記憶體,同時避開虛擬機對單張圖片快取大小的限制。

MemoryCache.java:以 LRU + 容量上限控管記憶體

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));
    private long size = 0;      // 目前佔用的位元組數
    private long limit = 1000000;

    public MemoryCache() {
        setLimit(Runtime.getRuntime().maxMemory() / 4);  // 上限為可用堆的 1/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();
        }
    }

    /** 超過上限時,由 iterator 由頭淘汰最近最少使用的那張圖 */
    private void checkSize() {
        if (size > limit) {
            Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
            while (iter.hasNext()) {
                size -= getSizeInBytes(iter.next().getValue());
                iter.remove();
                if (size <= limit) break;
            }
        }
    }

    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;
        return cache.get(id).get();
    }

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

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

兩者取捨在於「可控性」:SoftReference 交給 GC,程式碼簡單但何時被回收說不準;自訂 LRU 則能精準掌握記憶體曲線,個人較推薦後者。

FileCache.java:把圖片落到磁碟

public class FileCache {
    private File cacheDir;

    public FileCache(Context context) {
        // 有 SD 卡就在卡上開 LazyList 目錄,沒有則退回 app 的 cache 目錄
        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) {
        String filename = String.valueOf(url.hashCode());  // hashCode 當檔名
        return new File(cacheDir, filename);
    }

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

ImageLoader.java:把流程串起來

public class ImageLoader {
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    // 記錄 ImageView 目前對應的 url,用來防止清單捲動時的圖片錯位
    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);
    }

    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) {
        executorService.submit(new PhotosLoader(new PhotoToLoad(url, imageView)));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);
        Bitmap b = decodeFile(f);          // 1. 檔案快取
        if (b != null) return b;
        try {                              // 2. 網路下載
            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();
            os.flush();
            return decodeFile(f);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // 先只讀尺寸算出 inSampleSize,再實際解碼,避免大圖直接進記憶體
    private Bitmap decodeFile(File f) {
        try {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight, scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
            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;
            Activity a = (Activity) photoToLoad.imageView.getContext();
            a.runOnUiThread(new BitmapDisplayer(bmp, photoToLoad));  // 回主執行緒更新
        }
    }

    /** 若 ImageView 已被回收再利用給別的 url,就放棄這次結果 */
    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        return tag == null || !tag.equals(photoToLoad.url);
    }

    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        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) { }
    }
}

整體流程

先查記憶體快取 → 未命中則丟入線程池 → 查檔案快取 → 都沒有才走網路下載並寫檔 → 解碼時按比例縮圖 → 最後透過 runOnUiThread 回到主執行緒更新 ImageView。這條鏈路同時解決了「慢」、「爆記憶體」與「清單圖片錯位」三個痛點。

使用方式

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

最常見的擺放位置是 ListView/GridView 的 adapter 的 getView() 裡,一行就能完成異步載入與快取。

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