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

Android 網絡圖片異步加載實作解析

編輯:關於 Android 程式設計

前言

運氣不錯,入職一週後就能跟著兩位師兄做 Android 開發。師兄們都是高手,身為新人的我唯有多看多學多努力。前陣子忙得沒時間整理,今天剛完成 Android 客戶端的圖片異步加載類別,在這裡記錄一下(其實實現思路是參考網路上的開源方案)。

原理

在 ListView 或 GridView 中加載圖片,思路基本一致,三層快取逐層回退:

先從記憶體快取取得,取到就回傳;取不到則前往檔案快取,取到就回傳並同步更新記憶體快取;檔案快取也沒有,才從網絡下載,下載完成後同時更新記憶體快取與檔案快取。

流程圖如下:

線程數量要控制

在 ListView 中加載圖片,直覺做法是每張圖開一條線程,但快速滑動時極易造成 OOM。因此必須控制線程數量,方式是使用線程池,而線程池的大小要依處理器情況與業務特性自行判斷。

ExecutorService executorService = Executors.newFixedThreadPool(5);   // 5 可依情況調整

檔案快取類別

import java.io.File;
import android.content.Context;

public class FileCache {

    private static final String DIR_NAME = "your_dir";
    private File cacheDir;

    public FileCache(Context context) {
        // 找到用來保存快取圖片的目錄
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), DIR_NAME);
        } else {
            cacheDir = context.getCacheDir();
        }
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }

    public File getFile(String url) {
        // 以 url 的 hash code 作為檔名
        String filename = String.valueOf(url.hashCode());
        return new File(cacheDir, filename);
    }

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

記憶體快取類別

這裡使用軟引用 SoftReference。簡單說,它讓快取在記憶體緊張時可以被 GC 回收,不會造成洩漏。

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import android.graphics.Bitmap;

public class MemoryCache {

    private Map<String, SoftReference<Bitmap>> cache = Collections
            .synchronizedMap(new LinkedHashMap<String, SoftReference<Bitmap>>(10, 1.5f, true));

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

這裡用 LinkedHashMap 並把 accessOrder 設為 true,其實已經具備了 LRU 的雛形。後續 Android 官方提供了 LruCache,用強引用搭配容量上限,命中率和效能都比軟引用更好,是現在的首選。

圖片加載類別

package io.yunos.bbs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;

public class ImageLoader {

    /** 網絡逾時 */
    private static final int TIME_OUT = 30000;
    /** 預設圖片資源 */
    private static final int DEFAULT_BG = R.drawable.plate_list_head_bg;
    /** 線程池大小 */
    private static final int THREAD_NUM = 5;

    /** 記憶體圖片快取 */
    MemoryCache memoryCache = new MemoryCache();
    /** 檔案圖片快取 */
    FileCache fileCache;
    /** 判定 ImageView 是否被重用 */
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    /** 線程池 */
    ExecutorService executorService;
    /** 用來在 UI 線程顯示圖片的 Handler */
    Handler handler = new Handler();

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

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

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

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        // 先查檔案快取
        Bitmap bmp = decodeFile(f);
        if (bmp != null) {
            return bmp;
        }

        // 再走網絡
        try {
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(TIME_OUT);
            conn.setReadTimeout(TIME_OUT);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            copyStream(is, os);
            os.close();
            conn.disconnect();
            return decodeFile(f);
        } catch (Throwable ex) {
            if (ex instanceof OutOfMemoryError) {
                clearCache();
            }
            return null;
        }
    }

    private void copyStream(InputStream is, OutputStream os) {
        int buffer_size = 1024;
        try {
            byte[] bytes = new byte[buffer_size];
            while (true) {
                int count = is.read(bytes, 0, buffer_size);
                if (count == -1) {
                    break;
                }
                os.write(bytes, 0, count);
            }
        } catch (Exception e) {
            // 忽略
        }
    }

    private Bitmap decodeFile(File f) {
        try {
            FileInputStream fileInputStream = new FileInputStream(f);
            return BitmapFactory.decodeStream(fileInputStream);
        } catch (FileNotFoundException e) {
            return null;
        }
    }

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

    /** 佇列中的任務 */
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String url, ImageView imageView) {
            this.url = url;
            this.imageView = imageView;
        }
    }

    /** 異步載入圖片 */
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

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

        private boolean imageViewReused(PhotoToLoad photoToLoad) {
            String tag = imageViews.get(photoToLoad.imageView);
            if (tag == null || !tag.equals(photoToLoad.url)) {
                return true;
            }
            return false;
        }

        @Override
        public void run() {
            // 若 ImageView 已被重用於其他 url,放棄本次載入
            if (imageViewReused(photoToLoad)) {
                return;
            }
            Bitmap bitmap = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bitmap);
            if (imageViewReused(photoToLoad)) {
                return;
            }
            // 不能在子線程改動 UI
            BitmapDisplayer bd = new BitmapDisplayer(bitmap, photoToLoad);
            handler.post(bd);
        }

        class BitmapDisplayer implements Runnable {
            Bitmap bitmap;
            PhotoToLoad photoToLoad;

            public BitmapDisplayer(Bitmap bitmap, PhotoToLoad photoToLoad) {
                this.bitmap = bitmap;
                this.photoToLoad = photoToLoad;
            }

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

調用方式

ImageLoader imageLoader = new ImageLoader(context);
imageLoader.disPlayImage(imageUrl, imageView);

幾個值得深究的設計細節

imageViewReused 是整份程式碼最關鍵的一段。ListView 會重用 convertView,同一個 ImageView 可能先被指派 url A、再被指派 url B。如果 A 的下載較慢,等它回來時 ImageView 上顯示的其實已經是 B 的內容了,就會出現「圖片錯位」這個經典 bug。用 WeakHashMap 記錄每個 ImageView 目前對應的 url,回來後比對一次,就能擋掉錯誤的貼圖。

還缺一塊拼圖:圖片縮放。程式碼中的 decodeFile() 註解寫著 TODO,這其實是最容易 OOM 的地方。完整做法是先用 BitmapFactory.Options 搭配 inJustDecodeBounds = true 只讀取尺寸,計算縮放比例後設定 inSampleSize,再正式解碼。

現代替代方案。這套實作作為學習材料很有價值,但正式專案建議直接使用 Glide、Picasso 或 Fresco。它們把上述三層快取、線程池調度、ImageView 重用偵測、請求取消、生命週期綁定、GIF 支援、硬體位圖等細節都處理好了,還能自動隨容器大小解碼,省下大量邊角問題。

小結

最近終於開始忙起來了,我還是比較喜歡緊湊一點的節奏,能學到更多東西。

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