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

從零實現 ImageLoader:線程池、Bitmap 高效加載與二級緩存

編輯:關於 Android 程式設計

這次要動手做一個圖片加載器,其中會用到線程池、Bitmap 高效加載、LruCache 內存緩存與 DiskLruCache 磁盤緩存。出發之前,先把這四個知識點逐一理清。

一、線程池

線程池的優勢在於:(1)複用已有線程,避免頻繁創建與銷毀帶來的開銷;(2)有效控制最大並發數,避免大量線程爭搶資源而阻塞;(3)便於管理線程,並支持定時執行、定間隔循環執行等能力。

1. ThreadPoolExecutor 介紹
它是線程池的真正實現,構造方法如下:

 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory)

corePoolSize:核心線程數;maximumPoolSize:最大線程數,超出將阻塞;keepAliveTime:非核心線程的空閒超時時長,超時會被回收;unit:keepAliveTime 的時間單位,常用 TimeUnit.SECONDS、TimeUnit.MINUTES 等;workQueue:存放任務的隊列;threadFactory:創建新線程的工廠接口,只有一個 newThread(Runnable r) 方法。

2. ThreadPoolExecutor 典型配置

 private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { return new Thread(r, "ImageLoader#" + mCount.getAndIncrement()); } }; private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = CPU_COUNT + 1; private static final int MAX_POOL_SIZE = CPU_COUNT * 2 + 1; private static final long KEEP_ALIVE = 10L; public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor( CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, new LinkedBlockingDeque(), sThreadFactory);

二、Bitmap 高效加載

通過 BitmapFactory.Options 的 inSampleSize 採樣率,按需加載合適尺寸的圖片,避免一次性把大圖全部讀進內存。流程如下:

 public Bitmap decodeSampleBitmapFromResource(Resources resources, int resId, int reqWidth, int reqHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(resources, resId, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(resources, resId, options); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { int imageHeight = options.outHeight; int imageWidth = options.outWidth; int inSimpleSize = 1; if (imageHeight > reqHeight || imageWidth > reqWidth) { int halfHeight = imageHeight / 2; int halfWidth = imageWidth / 2; while ((halfHeight / inSimpleSize) >= reqHeight && (halfWidth / inSimpleSize) >= reqWidth) { inSimpleSize *= 2; } } return inSimpleSize; }

三、LruCache 內存緩存

Lru 即 Least Recently Used(近期最少使用)算法,核心思想是:當緩存期滿時,優先淘汰最近最少使用的對象。推薦使用 support-v4 包中的 LruCache,其底層是一個 LinkedHashMap。

 public class LruCache { private final LinkedHashMap map; public LruCache(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap(0, 0.75f, true); } public final V get(K key) { if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { mapValue = map.get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; } V createdValue = create(key); if (createdValue == null) { return null; } synchronized (this) { createCount++; mapValue = map.put(key, createdValue); if (mapValue != null) { map.put(key, mapValue); } else { size += safeSizeOf(key, createdValue); } } if (mapValue != null) { entryRemoved(false, key, createdValue, mapValue); return mapValue; } else { trimToSize(maxSize); return createdValue; } } public final V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } V previous; synchronized (this) { putCount++; size += safeSizeOf(key, value); previous = map.put(key, value); if (previous != null) { size -= safeSizeOf(key, previous); } } if (previous != null) { entryRemoved(false, key, previous, value); } trimToSize(maxSize); return previous; } public void trimToSize(int maxSize) { while (true) { K key; V value; synchronized (this) { if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } if (size <= maxSize || map.isEmpty()) { break; } Map.Entry toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } } public final V remove(K key) { if (key == null) { throw new NullPointerException("key == null"); } V previous; synchronized (this) { previous = map.remove(key); if (previous != null) { size -= safeSizeOf(key, previous); } } if (previous != null) { entryRemoved(false, key, previous, null); } return previous; } protected V create(K key) { return null; } public synchronized final Map snapshot() { return new LinkedHashMap(map); } }

讀完源碼,使用就很直觀了:

 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); int cacheSize = maxMemory / 8; mMemoryCache = new LruCache(cacheSize) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount() / 1024; } }; // 獲取緩存:mMemoryCache.get(key) // 添加緩存:mMemoryCache.put(key, bitmap)

四、DiskLruCache 磁盤緩存

內存緩存容量有限,磁盤緩存則能持久保存圖片,二者配合構成二級緩存。這裡同樣借用 Universal-ImageLoader 中的 DiskLruCache 實現。

1. DiskLruCache 的創建

 public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)

directory:存儲路徑;appVersion:通常為 1;valueCount:單個節點對應數據個數,通常為 1;maxSize:緩存總大小,例如 50MB。

 File diskCacheDir = getDiskCacheDir(mContext, "bitmap"); if (!diskCacheDir.exists()) { diskCacheDir.mkdirs(); } if (getUsableSpace(diskCacheDir) > DISK_CACHE_SIZE) { try { mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1, DISK_CACHE_SIZE); } catch (IOException e) { e.printStackTrace(); } }

其中 getDiskCacheDir 用於獲取磁盤緩存目錄,getUsableSpace 用於獲取可用空間,兩個方法的實現都在源碼包中。

2. DiskLruCache 緩存的添加
緩存的寫入通過 Editor 完成,Editor 是緩存對象的編輯器。

 String key = hashKeyForURI(uri); try { DiskLruCache.Editor editor = mDiskLruCache.edit(key); if (editor != null) { OutputStream outputStream = editor.newOutputStream(DISK_CACHE_INDEX); if (downloadURIToStream(uri, outputStream)) { editor.commit(); } else { editor.abort(); } mDiskLruCache.flush(); } } catch (IOException e) { return null; }

這段代碼把圖片寫入文件系統。有兩點值得說明:其一,把 uri 轉為 hashKey,是因為 uri 中可能含有影響使用的特殊字符;其二,downloadURIToStream 負責把圖片寫入文件系統,並配合 editor.commit 生效。

3. DiskLruCache 緩存的查找

 String key = hashKeyForURI(uri); try { DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key); if (snapshot != null) { FileInputStream fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX); FileDescriptor fileDescriptor = fileInputStream.getFD(); bitmap = mImageResizer.decodeSampleBitmapFromFileDescriptor(fileDescriptor, width, height); if (bitmap != null) { addBitmapToMemoryCache(key, bitmap); } } } catch (IOException e) { e.printStackTrace(); }

需要留意,這裡的 Snapshot 與 LruCache 的 Snapshot 不同:後者代表內存緩存的副本,前者只是一個保存了三個參數的對象。

至此,ImageLoader 主體已大致實現。源碼包中的 SquareImageView.java 用於得到一個寬高相同的 ImageView。同時,為優化列表滾動的卡頓,我們採用「僅當列表靜止時才加載圖片」的策略:

 public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { mIsGridViewIdle = true; adapter.notifyDataSetChanged(); } else { mIsGridViewIdle = false; } } // 在 getView 中判斷 if (mIsGridViewIdle) { imageLoader.bindBitmap(uri, imageView); }

運行效果如下。loadBitmapFromHttp 與 downloadBitmapFromURI 都能實現網絡加載:前者先寫入 disk 再讀取,後者先讀取再放入 memorycache。

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