編輯:關於 Android 程式設計
網路上關於 ImageLoader 的分析文章不少,但多數只停在「它怎麼用」或「它做了快取」。本文試著沿著源碼走一遍完整的載入路徑,把初始化、雙層快取、背景任務與解碼環節串起來,順帶說明幾個值得借鏡的設計細節。
ImageLoader 通常在 Application 的 onCreate() 中初始化一次,全域共用:
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context); config.threadPriority(Thread.NORM_PRIORITY - 2); config.denyCacheImageMultipleSizesInMemory(); config.diskCacheFileNameGenerator(new Md5FileNameGenerator()); config.diskCacheSize(50 * 1024 * 1024); // 50 MiB config.tasksProcessingOrder(QueueProcessingType.LIFO); config.writeDebugLogs(); // release 版本請移除 ImageLoader.getInstance().init(config.build());
值得注意的細節是 config.build():你沒有設定的欄位,會由內部的 initEmptyFieldsWithDefaultValues() 補上預設值,包括 downloader(負責下載)、decoder(負責解碼)等。這些物件在後面的流程中會被反覆呼叫,因此理解它們的職責,比記住 API 更重要。
public void displayImage(String uri, ImageView imageView, DisplayImageOptions options,
ImageLoadingListener listener, ImageLoadingProgressListener progressListener)
官方範例的選項配置如下:
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))
.build();
其中 displayer() 特別值得一看。它決定 Bitmap 最終如何呈現,而框架的實作方式是:把 Bitmap 畫進自訂的 Drawable,再把 Drawable 交給 ImageView,而不是直接操作 ImageView 的像素。這樣做的好處是與現有的 View 體系解耦,效能也更可控。
public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {
if (!(imageAware instanceof ImageViewAware)) {
throw new IllegalArgumentException("ImageAware should wrap ImageView. ImageViewAware is expected.");
}
imageAware.setImageDrawable(new CircleDrawable(bitmap, strokeColor, strokeWidth));
}
繼續往下看,會發現真正被呼叫的是這個多帶了兩個參數的重載版本:
public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,
ImageSize targetSize, ImageLoadingListener listener,
ImageLoadingProgressListener progressListener)
ImageView 被換成了 ImageAware。這是整個框架最值得稱讚的設計之一:它把 ImageView 用弱引用包起來。
為什麼要弱引用?想像一個場景:某個列表項的父 View 已經被回收,但 ImageLoader 的背景執行緒還在等待下載完成、準備把圖片設回 ImageView。此時若 ImageLoader 強引用著這個 ImageView,ImageView 與它的父 View 都無法釋放,記憶體洩漏就這樣發生了。用弱引用包住,等待的過程就不會成為回收的障礙。
displayImage 的核心流程(節錄)大致如下:
if (targetSize == null) {
// 依 ImageView 的實際寬高與設定的最大尺寸,換算出目標圖片尺寸
targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());
}
// 以 uri + 尺寸產生快取 key
String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);
listener.onLoadingStarted(uri, imageAware.getWrappedView());
// 第一層:記憶體快取(基於 LRU,內部以 LinkedHashMap 實作)
Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);
if (bmp != null && !bmp.isRecycled()) {
if (options.shouldPostProcess()) {
// 需要後處理時,包裝成任務交給執行緒池
ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(...);
if (options.isSyncLoading()) displayTask.run();
else engine.submit(displayTask);
} else {
options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);
listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);
}
} else {
// 第二層:磁碟快取
if (options.shouldShowImageOnLoading()) {
imageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));
} else if (options.isResetViewBeforeLoading()) {
imageAware.setImageDrawable(null);
}
LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo, defineHandler(options));
if (options.isSyncLoading()) displayTask.run();
else engine.submit(displayTask);
}
記憶體命中就立刻顯示,未命中則先顯示佔位圖,再把任務丟進執行緒池。這個「先給回饋、再慢慢補」的順序,是列表捲動體驗流暢的關鍵。
loadFromUriLock.lock();
try {
checkTaskNotActual(); // 這個 ImageView 是否已被回收或複用?
Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);
if (bmp == null || bmp.isRecycled()) {
bmp = tryLoadBitmap(); // 先查磁碟快取,沒有才走網路下載
if (bmp == null) return;
if (options.shouldPreProcess()) {
bmp = options.getPreProcessor().process(bmp);
}
if (bmp != null && options.isCacheInMemory()) {
configuration.memoryCache.put(memoryCacheKey, bmp);
}
} else {
loadedFrom = LoadedFrom.MEMORY_CACHE;
}
if (bmp != null && options.shouldPostProcess()) {
bmp = options.getPostProcessor().process(bmp);
}
checkTaskNotActual();
checkTaskInterrupted();
} catch (TaskCancelledException e) {
fireCancelEvent();
return;
} finally {
loadFromUriLock.unlock();
}
DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
runTask(displayBitmapTask, syncLoading, handler, engine); // 設定圖片的動作必須回到主執行緒
這段程式碼裡有兩個設計值得學。一是 checkTaskNotActual():列表捲動時 ImageView 會被反覆複用,同一個 View 可能先後被指派給好幾個不同的圖片請求,若不檢查,就會出現「A 位置的圖片跑到 B 位置」的經典錯位。二是 loadFromUriLock:同一個 uri 只用一把鎖,讓重複請求自動排隊共用結果,避免同一張圖被下載五次。
File imageFile = configuration.diskCache.get(uri);
if (imageFile != null && imageFile.exists() && imageFile.length() > 0) {
loadedFrom = LoadedFrom.DISC_CACHE;
bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));
}
if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
loadedFrom = LoadedFrom.NETWORK;
String imageUriForDecoding = uri;
if (options.isCacheOnDisk() && tryCacheImageOnDisk()) {
imageFile = configuration.diskCache.get(uri);
if (imageFile != null) {
imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath());
}
}
bitmap = decodeImage(imageUriForDecoding);
if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
fireFailEvent(FailType.DECODING_ERROR, null);
}
}
注意它的順序:即使設定了 cacheOnDisk,也是先把圖存到磁碟、再從磁碟檔案解碼,而不是直接讀網路串流。這樣做讓解碼邏輯只有一條路徑,程式碼簡單,也更容易在解碼前調整尺寸。
InputStream imageStream = getImageStream(decodingInfo); ImageInfo imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo); // 第一次讀取已經把串流推到盡頭,必須重置才能再用 imageStream = resetStream(imageStream, decodingInfo); Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo); decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions);
這裡有兩個關鍵點。第一,getImageStream() 拿到的是 BufferedInputStream,支援 mark()/reset(),因此第一次讀出尺寸後可以重置回起點,讓第二次解碼重用同一條串流;若不支援 mark,就只能重新下一次載。第二,解碼時透過 BitmapFactory.Options 的 inSampleSize 做縮放,避免把一張 4000px 的圖原封不動塞進 100dp 的 ImageView——這是 OOM 最常見的來源。
InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
if (is == null) return false;
try {
return configuration.diskCache.save(uri, is, this);
} finally {
IoUtils.closeSilently(is);
}
BaseImageDownloader 依 uri 的 scheme 分派處理:http/https 走網路、file 走本機、content 走 ContentProvider、assets 與 drawable 走資源,其餘交給 getStreamFromOtherSource。網路分支裡它把串流層層包成 BufferedInputStream 與 ContentLengthInputStream,前者提供 mark/reset 能力,後者讓進度回呼知道總長度。
而進度監聽的奧妙就在 diskCache.save():save 把輸入流寫入輸出流的過程中,會回呼 CopyListener 的 onByteCopies(),LoadAndDisplayImageTask 在這裡實作了該介面,再把它轉發給你傳入的 progressListener。所以進度條更新的真相是——它其實發生在磁碟寫入的過程中。
如果磁碟寫入後還需要縮圖,resizeAndSaveImage() 會以 targetImageSize 重新解碼、可選地跑一次 processorForDiskCache,再把處理後的 Bitmap 覆寫回快取,並立刻 recycle 暫存物件。
把整條路徑串起來看,ImageLoader 的設計骨架其實只有三件事:用 ImageAware 弱引用解決生命週期問題、用記憶體加磁碟的雙層快取換取速度、用執行緒池與 handler 把背景工作與 UI 更新乾淨切開。理解這三點,即使你今天用的是 Glide 或 Fresco,也一樣能讀懂它們在做什麼。
自定義控件實戰(四):打造通訊錄字母快速索引欄 QuickIndexBar
自定義View通訊錄字母快速索引 在 Android 日常開發中,我們經常在聯繫人界面看到側邊的字母導航欄。當用戶點擊某個字母時,列表會依據漢字的首字母拼音快速定位到對
Android 使用 WebView 播放 Flash 及偵測外掛的方法
本文分享一個實例:如何在 Android 中用 WebView 播放 Flash,並在未安裝 Flash 外掛時提示使用者前往市集安裝。 問題描述 最近幫同學做專案,順手
Android 開發筆記(一百一十九):Toolbar 與新版 SearchView 用法全解
Toolbar 此前在《Android 開發筆記(二十)頂部導航欄》中我們學過 ActionBar,但 ActionBar 實在不太好用:文字風格不能定製、圖標不能替換,
用 android-async-http 實作登入:GET 與 POST 兩種寫法完整示範
在〈android-async-http 開源庫介紹與用法〉一文中,我們已經認識了這個庫的基本結構。本文直接進入實戰,用「登入」這個最常見的場景,把 AsyncHttpC