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

Android 網路圖片載入優化:執行緒池、雙層快取與解析度縮放

編輯:關於 Android 程式設計

在 ListView 或 GridView 裡載入網路圖片,若直接把下載寫在主執行緒,畫面一定卡。網路上常見的解法就是「背景執行緒 + 快取」,本文在這個基礎上再往前優化四步:


1. 以執行緒池取代每次新增 Thread,控制併發數量、避免無限擴張。
2. 記憶體快取與檔案快取雙層並用,二級快取命中就不必再走網路。
3. 記憶體快取嚴格限制在可用堆積的四分之一,並以 LRU 淘汰最久未用的項目。
4. 解碼時按比例縮放,只留畫面真正需要的大小,大幅降低記憶體佔用。

一、記憶體快取:以 LRU 嚴格控管用量

這裡刻意不用 SoftReference,而是自己記帳:用 LinkedHashMap 的存取順序模式實作 LRU,再搭配一個 size 變數隨時掌握已用位元組數,超過上限就從最舊的那一端淘汰。這樣做的好處是記憶體用量完全可控,不會等到系統回收才發現已經爆掉。

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);
    }

    public void setLimit(long new_limit) {
        limit = new_limit;
        Log.i(TAG, "MemoryCache will use up to " + limit / 1024f / 1024f + "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 版本:記憶體何時被回收、回收多少,都由自己決定,行為可預期。

二、檔案快取:把圖片落地到本機

有 SD 卡時在卡上開一個資料夾存放快取圖片,沒有就退回系統的應用程式快取目錄。檔名直接取網址的 hashCode(),省下處理特殊字元的麻煩。

public class FileCache {

    private File cacheDir;

    public FileCache(Context context) {
        // 有記憶卡就放在卡上的 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) {
        // 以網址的 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();
    }
}

三、核心:ImageLoader

這個類別把前面兩層快取、執行緒池、UI 執行緒更新以及「防止圖片錯位」全部串起來。載入順序是:記憶體 → 檔案 → 網路,任何一層命中就不再往下走。

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) {
            e.printStackTrace();
        }
        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 回收再利用時,同一個 ImageView 可能已被配到別的網址,
     * 這裡比對 tag 避免圖片錯位
     */
    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) {
            ex.printStackTrace();
        }
    }
}

四、整體流程與使用方式

流程可以濃縮成一句話:先查記憶體快取,沒有就開背景執行緒;背景執行緒先查檔案快取,還是沒有才真的下載,下載完順手做縮放處理,最後透過 runOnUiThread() 把結果刷回畫面。

a.runOnUiThread(...);

在專案中的基本用法只需兩行:

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

最常見的擺放位置是 ListView 轉接器的 getView() 裡,GridView 也完全適用。想釋放資源時呼叫 imageLoader.clearCache() 即可同時清空兩層快取。

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