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

Android 圖片加載優化實戰:二級緩存搭配異步加載

編輯:關於 Android 程式設計

一、問題從哪裡來

凡是列表頁、資訊流、畫廊這類場景,幾乎都要從網路拉取大量圖片。如果每次滑動都重新發一次請求,畫面不僅容易掉幀,用戶的流量也吃不消。實務上常見的解法是「二級緩存 + 異步加載」:先問內存,內存撲空再問本地檔案,兩邊都沒有才真正走網路。

一級緩存(內存)本質上就是一個以圖片 URL 為 key、Bitmap 為 value 的 Map。它最快,但直接持有大量位圖很容易把堆撐爆,因此管理上要多花心思——要嘛採用成熟的三方元件,要嘛自己實作一套帶容量上限與回收策略的機制。二級緩存(檔案)邏輯單純得多,把圖片寫進磁碟、下次直接讀檔即可,自己封裝一個小類就能勝任。

二、案例場景

本文以新聞列表的縮略圖為例,走一遍完整流程。

三、核心元件拆解

1. MemoryCache:一級緩存

用一個 LinkedHashMap 承載圖片,並覆寫 removeEldestEntry() 控制上限; value 包一層 SoftReference,讓記憶體吃緊時系統能優先回收這些位圖。

public class MemoryCache {
    private static final int MAX_CACHE_CAPACITY = 30;

    private HashMap<String, SoftReference<Bitmap>> mCacheMap =
            new LinkedHashMap<String, SoftReference<Bitmap>>() {
        private static final long serialVersionUID = 1L;

        @Override
        protected boolean removeEldestEntry(
                Map.Entry<String, SoftReference<Bitmap>> eldest) {
            return size() > MAX_CACHE_CAPACITY;
        }
    };

    /** 命中且未被回收才回傳,否則回 null */
    public Bitmap get(String id) {
        if (!mCacheMap.containsKey(id)) return null;
        SoftReference<Bitmap> ref = mCacheMap.get(id);
        return ref.get();
    }

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

    /** 清空並回收所有快取 */
    public void clear() {
        try {
            for (Map.Entry<String, SoftReference<Bitmap>> entry : mCacheMap.entrySet()) {
                SoftReference<Bitmap> sr = entry.getValue();
                if (sr != null) {
                    Bitmap bmp = sr.get();
                    if (bmp != null) bmp.recycle();
                }
            }
            mCacheMap.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. FileCache:二級緩存

有 SD 卡就把圖片寫到外接儲存,沒有就退回 context.getCacheDir()。URL 先做 URLEncode,順便解決中文路徑與特殊字元的問題。

public class FileCache {
    private File mCacheDir;

    public FileCache(Context context, File cacheDir, String dir) {
        if (android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED)) {
            mCacheDir = new File(cacheDir, dir);
        } else {
            mCacheDir = context.getCacheDir();
        }
        if (!mCacheDir.exists()) mCacheDir.mkdirs();
    }

    public File getFile(String url) {
        File f = null;
        try {
            String filename = URLEncoder.encode(url, "utf-8");
            f = new File(mCacheDir, filename);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return f;
    }

    public void clear() {
        File[] files = mCacheDir.listFiles();
        for (File f : files) f.delete();
    }
}

3. AsyncImageLoader:把異步流程串起來

Android 採用單執行緒模型,UI 執行緒必須即時回應,否則會觸發 ANR。圖片讀檔與網路下載都屬於耗時操作,不能丟在主執行緒上跑。這裡不用 AsyncTask,而是手寫「固定大小執行緒池 + 任務佇列 + Handler 回呼」,好把執行緒間通訊的本質看清楚。

public class AsyncImageLoader {
    private MemoryCache mMemoryCache;
    private FileCache mFileCache;
    private ExecutorService mExecutorService;

    /** 記錄每個 ImageView 目前對應的 url,避免列表復用時圖片錯位 */
    private Map<ImageView, String> mImageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());

    /** 正在下載的任務,用來去重 */
    private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>();

    public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) {
        mMemoryCache = memoryCache;
        mFileCache = fileCache;
        mExecutorService = Executors.newFixedThreadPool(5);
    }

    public Bitmap loadBitmap(ImageView imageView, String url) {
        mImageViews.put(imageView, url);
        Bitmap bitmap = mMemoryCache.get(url);
        if (bitmap == null) {
            enquequeLoadPhoto(url, imageView);
        }
        return bitmap;
    }

    private void enquequeLoadPhoto(String url, ImageView imageView) {
        if (isTaskExisted(url)) return;
        LoadPhotoTask task = new LoadPhotoTask(url, imageView);
        synchronized (mTaskQueue) {
            mTaskQueue.add(task);
        }
        mExecutorService.execute(task);
    }

    private boolean isTaskExisted(String url) {
        if (url == null) return false;
        synchronized (mTaskQueue) {
            int size = mTaskQueue.size();
            for (int i = 0; i < size; i++) {
                if (url.equals(mTaskQueue.get(i).url)) return true;
            }
        }
        return false;
    }

    private class LoadPhotoTask implements Runnable {
        String url;
        ImageView imageView;

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

        @Override
        public void run() {
            File f = mFileCache.getFile(url);
            Bitmap bmp = getBitmapByUrl(url);
            synchronized (mTaskQueue) {
                mTaskQueue.remove(this);
            }
            if (bmp != null && imageView != null
                    && url.equals(mImageViews.get(imageView))) {
                mMemoryCache.put(url, bmp);
                // 回到主執行緒更新 UI
            }
        }
    }

    public void destroy() {
        mMemoryCache.clear();
        mExecutorService.shutdownNow();
        mImageViews.clear();
        mTaskQueue.clear();
    }
}

封裝完成後,對外只需要一個 loadBitmap(),呼叫端非常乾淨。把註解讀透,Android 執行緒間的異步通訊其實就那麼回事。

4. ImageUtil:網路抓取與磁碟讀寫

public class ImageUtil {
    public static Bitmap loadBitmapFromWeb(String url, File file) {
        HttpURLConnection conn = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            URL imageUrl = new URL(url);
            conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            is = conn.getInputStream();
            os = new FileOutputStream(file);
            copyStream(is, os);
            return decodeFile(file);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (os != null) os.close();
                if (is != null) is.close();
                if (conn != null) conn.disconnect();
            } catch (IOException e) { }
        }
    }

    public static Bitmap decodeFile(File f) {
        try {
            return BitmapFactory.decodeStream(new FileInputStream(f), null, null);
        } catch (Exception e) { }
        return null;
    }

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

四、元件之間怎麼協作

MainActivity

public class MainActivity extends Activity {
    ListView list;
    ListViewAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list = (ListView) findViewById(R.id.list);
        adapter = new ListViewAdapter(this, mStrings);
        list.setAdapter(adapter);
    }

    @Override
    public void onDestroy() {
        list.setAdapter(null);
        super.onDestroy();
        adapter.destroy();
    }

    private String[] mStrings = {
        "https://news.21-sun.com/UserFiles/x_Image/x_20150606083511_0.jpg",
        "https://news.21-sun.com/UserFiles/x_Image/x_20150606082847_0.jpg"
        // ... 其餘 url
    };
}

ListViewAdapter

注意 setTag() 的用法:異步回來之後要比對 tag 是否仍等於當前 url,否則列表滑動時會出現「圖片貼錯格子」的經典 bug。

public class ListViewAdapter extends BaseAdapter {
    private Activity mActivity;
    private String[] data;
    private LayoutInflater inflater;
    private AsyncImageLoader imageLoader;

    public ListViewAdapter(Activity mActivity, String[] d) {
        this.mActivity = mActivity;
        data = d;
        inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        MemoryCache mcache = new MemoryCache();
        File sdCard = android.os.Environment.getExternalStorageDirectory();
        File cacheDir = new File(sdCard, "jereh_cache");
        FileCache fcache = new FileCache(mActivity, cacheDir, "news_img");
        imageLoader = new AsyncImageLoader(mActivity, mcache, fcache);
    }

    public int getCount() { return data.length; }
    public Object getItem(int position) { return position; }
    public long getItemId(int position) { return position; }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item, null);
            vh = new ViewHolder();
            vh.tvTitle = (TextView) convertView.findViewById(R.id.text);
            vh.ivImg = (ImageView) convertView.findViewById(R.id.image);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        vh.tvTitle.setText("標題資訊測試—— " + position);
        vh.ivImg.setTag(data[position]);

        Bitmap bmp = imageLoader.loadBitmap(vh.ivImg, data[position]);
        if (bmp == null) {
            vh.ivImg.setImageResource(R.drawable.default_big);
        } else {
            vh.ivImg.setImageBitmap(bmp);
        }
        return convertView;
    }

    private class ViewHolder {
        TextView tvTitle;
        ImageView ivImg;
    }

    public void destroy() {
        imageLoader.destroy();
    }
}

想動手驗證效果的朋友,建議把原始碼拉下來實際跑一次,快取命中與未命中的差異會非常明顯。

疑問諮詢或技術交流,歡迎加入官方 QQ 群:(452379712)

作者:傑瑞教育
出處:https://blog.csdn.net/jerehedu/
本文版權歸煙台傑瑞教育科技有限公司與 CSDN 共有,歡迎轉載,但未經作者同意必須保留此段聲明,並在文章頁面明顯位置給出原文連結,否則保留追究法律責任的權利。

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