編輯:Android 資訊
ImageLoader 系列寫到這裡,基本架構與加載流程都已經鋪完,只剩最後一塊拼圖:緩存。為了用戶體驗,下載過的圖片通常都要留一份,內存和本地各存一層是常見做法。而既然是框架,可定制性就必須到位——於是又回到那個熟悉的答案:抽象。
在《圖片加載與加載策略》中我們談過 AbsLoader 的通用邏輯,其中就包含緩存環節,因此 AbsLoader 必然持有緩存對象的引用:
public abstract class AbsLoader implements Loader {
/** 圖片緩存 */
private static BitmapCache mCache = SimpleImageLoader.getInstance().getConfig().bitmapCache;
// 代碼省略
}
這裡用 static 是因為無論有多少個 Loader,緩存都應該只有一份、全局共享。
接口本身非常樸素:
public interface BitmapCache {
public Bitmap get(BitmapRequest key);
public void put(BitmapRequest key, Bitmap value);
public void remove(BitmapRequest key);
}
只聲明了取、存、刪三個動作。這裡依賴了一個 BitmapRequest 類,它代表一次圖片加載請求,內部持有對應的 ImageView、圖片 uri、顯示 Config 等信息。緩存以圖片 uri 為 key、Bitmap 為 value,同時借助 ImageView 的寬高來實現按尺寸加載。
之所以要定義接口,還是為了可擴展——面向接口編程的思路又一次登場。不妨先自己想一遍:如果換成你,會怎麼設計、怎麼實現?動手寫一遍,體會會深得多。
框架要接住用戶千奇百怪的需求,但也該有合理的默認實現。內存緩存就是其中之一:把已加載的圖片留在內存,能大幅提高重複加載的速度。策略上我們選用 LRU 算法,直接複用 support-v4 中的 LruCache:
public class MemoryCache implements BitmapCache {
private LruCache<String, Bitmap> mMemeryCache;
public MemoryCache() {
// 可用最大內存,單位 KB
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// 取四分之一的可用內存作為緩存
final int cacheSize = maxMemory / 4;
mMemeryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
};
}
@Override public Bitmap get(BitmapRequest key) { return mMemeryCache.get(key.imageUri); }
@Override public void put(BitmapRequest key, Bitmap value) { mMemeryCache.put(key.imageUri, value); }
@Override public void remove(BitmapRequest key) { mMemeryCache.remove(key.imageUri); }
}
只有內存緩存是不夠的。把圖片落到本地,用戶下次進入應用時就能直接從磁盤讀取,既省流量又省時間。這裡我們用了 Jake Wharton 的 DiskLruCache:
public class DiskCache implements BitmapCache {
/** 1MB */
private static final int MB = 1024 * 1024;
/** 緩存目錄名 */
private static final String IMAGE_DISK_CACHE = "bitmap";
private DiskLruCache mDiskLruCache;
private static DiskCache mDiskCache;
private DiskCache(Context context) { initDiskCache(context); }
public static DiskCache getDiskCache(Context context) {
if (mDiskCache == null) {
synchronized (DiskCache.class) {
if (mDiskCache == null) mDiskCache = new DiskCache(context);
}
}
return mDiskCache;
}
/** 初始化 sdcard 緩存 */
private void initDiskCache(Context context) {
try {
File cacheDir = getDiskCacheDir(context, IMAGE_DISK_CACHE);
if (!cacheDir.exists()) cacheDir.mkdirs();
mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 50 * MB);
} catch (IOException e) {
e.printStackTrace();
}
}
/** 掛載了 sdcard 就用外部緩存目錄,否則退回應用私有目錄 */
public File getDiskCacheDir(Context context, String uniqueName) {
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
cachePath = context.getExternalCacheDir().getPath();
} else {
cachePath = context.getCacheDir().getPath();
}
return new File(cachePath + File.separator + uniqueName);
}
@Override
public synchronized Bitmap get(final BitmapRequest bean) {
BitmapDecoder decoder = new BitmapDecoder() {
@Override
public Bitmap decodeBitmapWithOption(Options options) {
final InputStream inputStream = getInputStream(bean.imageUriMd5);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
IOUtil.closeQuietly(inputStream);
return bitmap;
}
};
return decoder.decodeBitmap(bean.getImageViewWidth(), bean.getImageViewHeight());
}
private InputStream getInputStream(String md5) {
try {
Snapshot snapshot = mDiskLruCache.get(md5);
if (snapshot != null) return snapshot.getInputStream(0);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void put(BitmapRequest key, Bitmap value) { /* 代碼省略 */ }
public void remove(BitmapRequest key) { /* 代碼省略 */ }
}
邏輯很直白:實現 BitmapCache,內部包一層 DiskLruCache 完成文件的增刪查。
按 ImageView 尺寸加載圖片,標準流程是三步:
BitmapFactory.Options,設 inJustDecodeBounds = true,只解析尺寸等信息;inJustDecodeBounds = false,按比例真正加載。我們用模板方法把這個過程封裝起來,用戶只需繼承並覆寫 decodeBitmapWithOption:
public abstract class BitmapDecoder {
public abstract Bitmap decodeBitmapWithOption(Options options);
/**
* @param width 目標寬度
* @param height 目標高度
*/
public Bitmap decodeBitmap(int width, int height) {
// 請求原圖則直接加載
if (width <= 0 || height <= 0) return decodeBitmapWithOption(null);
// 1. 只解析邊界信息的 Options
BitmapFactory.Options options = getJustDecodeBoundsOptions();
// 2. 第一次解析,返回的 bitmap 為空,數據寫入 options
decodeBitmapWithOption(options);
// 3. 計算縮放比例,並關閉 bounds-only 模式
calculateInSmall(options, width, height);
// 4. 按縮放比例真正加載
return decodeBitmapWithOption(options);
}
private Options getJustDecodeBoundsOptions() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
return options;
}
protected void calculateInSmall(Options options, int width, int height) {
options.inSampleSize = computeInSmallSize(options, width, height);
options.inPreferredConfig = Config.RGB_565;
options.inJustDecodeBounds = false;
options.inPurgeable = true;
options.inInputShareable = true;
}
private int computeInSmallSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
final float totalPixels = width * height;
// 超過目標像素兩倍時進一步壓縮
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
}
把這套重複又瑣碎的流程收攏到一個類裡,既簡化了調用方代碼,也讓邏輯有了複用的可能——模板方法模式的一個不錯示範。
有了內存與磁盤兩層,其實還差一步:把它們組合起來,兩者的優點就都拿到了。
public class DoubleCache implements BitmapCache {
DiskCache mDiskCache;
MemoryCache mMemoryCache = new MemoryCache();
public DoubleCache(Context context) {
mDiskCache = DiskCache.getDiskCache(context);
}
@Override
public Bitmap get(BitmapRequest key) {
Bitmap value = mMemoryCache.get(key);
if (value == null) {
value = mDiskCache.get(key);
// 從磁盤讀到之後回填內存
saveBitmapIntoMemory(key, value);
}
return value;
}
private void saveBitmapIntoMemory(BitmapRequest key, Bitmap bitmap) {
if (bitmap != null) mMemoryCache.put(key, bitmap);
}
@Override public void put(BitmapRequest key, Bitmap value) {
mDiskCache.put(key, value);
mMemoryCache.put(key, value);
}
@Override public void remove(BitmapRequest key) {
mDiskCache.remove(key);
mMemoryCache.remove(key);
}
}
緩存策略本就多樣,框架要留出注入的口子。只要實現 BitmapCache,就能通過 ImageLoaderConfig 塞進 ImageLoader:
private void initImageLoader() {
ImageLoaderConfig config = new ImageLoaderConfig()
.setLoadingPlaceholder(R.drawable.loading)
.setNotFoundPlaceholder(R.drawable.not_found)
.setCache(new MyCache());
SimpleImageLoader.getInstance().init(config);
}
MyCache.java
public class MyCache implements BitmapCache {
@Override public Bitmap get(BitmapRequest key) { /* 你的邏輯 */ }
@Override public void put(BitmapRequest key, Bitmap value) { /* 你的邏輯 */ }
@Override public void remove(BitmapRequest key) { /* 你的邏輯 */ }
}
系列到此收尾。從基本架構、具體實現到設計取捨,我們完整走了一遍一個簡單但可擴展的 ImageLoader 該長什麼樣子。建議你照著自己實現一遍,過程中一定會撞見一些只在動手時才會暴露的問題,理解也會隨之加深。
如果看完這個系列,你能體會到面向對象的基本原則與設計思考,而不是僅僅收穫「又找到一個可以複製的 ImageLoader」,那這些分享就達到了目的。
Android Paint 使用詳解:屬性、樣式與常用方法全整理
自訂控制項的靈活性極高,只要有想法就能畫出各種圖形。而在 Android 自訂控制項的開發中,Paint 這個類的使用頻率相當高。本篇就來系統梳理一下 Paint 的用法
Android UI 元件系列:ProgressBar 進度條
當 Android 執行一些背景作業時,例如載入遊戲、播放音樂,使用者往往無法得知目前的執行進度。這時就能透過進度條來即時呈現這些資訊。 Android 系統提供兩種進度
Android 安全加密:非對稱加密與 RSA 原理實戰
Android 安全加密系列文章索引 Android 安全加密:對稱加密 Android 安全加密:非對稱加密 Android 安全加密:消息摘要 Message Di
Android 性能優化全景指南:UI、內存、代碼與電量
一、寫在前面 寫這篇有點矛盾。網上隨手一搜,性能優化建議铺天盖地,但多數文章的通病是只給結論——什麼不能用、什麼該怎麼用,卻很少真正做系統的案例剖析,讀者往往只能死記規則