編輯:關於 Android 程式設計
剛接觸 Android 時,看到專案裡用到了 ImageLoader 這個圖片緩存外掛。抱著「知其然更要知其所以然」的想法,我曾經下載它的源碼去研究,但最終因對 Android 相關知識了解有限而作罷。本篇不會過於深入,只是對 ImageLoader 的創建過程稍作梳理,方便日後使用。
從使用的源頭說起。ImageLoader 提供了如下載入並展示圖片的方法:

通常我們會使用前幾個方法,至於接收 ImageView 的那些重載,則會先將 ImageView 包裝成 ImageAware 再使用。查看源碼:
public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) { displayImage(uri, new ImageViewAware(imageView), options, null, null); }
它把 imageView 封裝成 ImageViewAware 後,呼叫了參數最完整的方法:
public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener)
所以直接分析這個方法即可。進入後首先會執行 checkConfiguration(),檢測 configuration 是否為 null,若為 null 則拋出異常:
private void checkConfiguration() { if (configuration == null) { throw new IllegalStateException(ERROR_NOT_INIT); } }
那麼這個 configuration 是什麼?它就是 ImageLoaderConfiguration。使用 ImageLoader 時,首先要在某處(例如 Application 的 onCreate)配置 ImageLoaderConfiguration,用來初始化緩存策略、可緩存檔案數量等參數。簡單配置如下:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext) .threadPoolSize(Thread.NORM_PRIORITY - 2) .threadPriority(Thread.NORM_PRIORITY - 2) .memoryCache(new WeakMemoryCache()) .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) .diskCache(new UnlimitedDiscCache(cacheDir)) .build(); ImageLoader.getInstance().init(config);
這明顯是 Builder 模式的應用。Builder 模式的好處之一,是可以對較複雜的物件逐步創建各個小組件,再由這些組件最終完成複雜物件的初始化。build() 方法也很簡單:
public ImageLoaderConfiguration build() { initEmptyFieldsWithDefaultValues(); return new ImageLoaderConfiguration(this); }
build 方法做了兩件事:
1)透過 initEmptyFieldsWithDefaultValues() 設定一些預設參數(前提是你在構建過程中沒有自行配置)。例如若沒有呼叫 imageDownloader 配置自己的下載邏輯,就會採用 ImageLoader 預設的下載方式:
if (downloader == null) { downloader = DefaultConfigurationFactory.createImageDownloader(context); }
2)返回 ImageLoaderConfiguration 物件。其建構子是 private 的,類別為 final,且所有屬性皆為 final,一旦 build 完成便不可更改:
private ImageLoaderConfiguration(final Builder builder) { resources = builder.context.getResources(); maxImageWidthForMemoryCache = builder.maxImageWidthForMemoryCache; maxImageHeightForMemoryCache = builder.maxImageHeightForMemoryCache; ... diskCache = builder.diskCache; memoryCache = builder.memoryCache; defaultDisplayImageOptions = builder.defaultDisplayImageOptions; downloader = builder.downloader; decoder = builder.decoder; ... networkDeniedDownloader = new NetworkDeniedImageDownloader(downloader); slowNetworkDownloader = new SlowNetworkImageDownloader(downloader); }
接著是大家熟悉的 DisplayImageOptions。如果使用 displayImage 時沒有傳入自定義的 DisplayImageOptions,就會使用預設物件:
if (options == null) { options = configuration.defaultDisplayImageOptions; }
這個預設的 DisplayImageOptions 由 Builder 創建的 ImageLoaderConfiguration 初始化:
final DisplayImageOptions defaultDisplayImageOptions; private ImageLoaderConfiguration(final Builder builder) { defaultDisplayImageOptions = builder.defaultDisplayImageOptions; }
你可透過 Builder 的 defaultDisplayImageOptions 方法完成初始化:
public Builder defaultDisplayImageOptions(DisplayImageOptions defaultDisplayImageOptions) { this.defaultDisplayImageOptions = defaultDisplayImageOptions; return this; }
那麼問題來了:如果創建 Builder 時沒有呼叫 defaultDisplayImageOptions(),豈不是為 null?還記得 build() 裡呼叫的 initEmptyFieldsWithDefaultValues() 嗎?它確保了 defaultDisplayImageOptions 不為 null:
if (defaultDisplayImageOptions == null) { defaultDisplayImageOptions = DisplayImageOptions.createSimple(); } public static DisplayImageOptions createSimple() { return new Builder().build(); }
這裡的 createSimple 同樣是 Builder 模式的應用。至此,ImageLoaderConfiguration 的創建才算真正完成。
ImageLoader 是一個單例類別,透過如下方式完成初始化:
ImageLoader.getInstance().init(ImageLoaderConfiguration)
看看 init 方法做了什麼:
public synchronized void init(ImageLoaderConfiguration configuration) { if (configuration == null) { throw new IllegalArgumentException(ERROR_INIT_CONFIG_WITH_NULL); } if (this.configuration == null) { engine = new ImageLoaderEngine(configuration); this.configuration = configuration; } }
很簡單,就是把 configuration 賦給 ImageLoader.configuration 引用。至此 ImageLoader 與 ImageLoaderConfiguration 都初始化完畢,可以放心呼叫 displayImage 了。
這裡分享一個實用技巧:如果你的應用裡圖片的失敗圖、加載中圖等樣式有許多相似之處,可以透過 Builder 的 defaultDisplayImageOptions 指定預設 Options;個別頁面若需不同風格,再呼叫 displayImage 的其他重載方法傳入對應的 DisplayImageOptions 即可:
private void initImageLoader(Context context) { DisplayImageOptions options = new DisplayImageOptions.Builder().build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).defaultDisplayImageOptions(options).build(); ImageLoader.getInstance().init(config); }
終於進入核心工作:展示圖片。先看圖片資源地址為 null 的情況:
if (TextUtils.isEmpty(uri)) { engine.cancelDisplayTaskFor(imageAware); listener.onLoadingStarted(uri, imageAware.getWrappedView()); if (options.shouldShowImageForEmptyUri()) { imageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources)); } else { imageAware.setImageDrawable(null); } listener.onLoadingComplete(uri, imageAware.getWrappedView(), null); return; }
如果在配置 DisplayImageOptions 時呼叫了 showImageForEmptyUri,就讓 ImageView 顯示指定的佔位圖,否則什麼都不顯示。仔看得話,上面也提供了 listener.onLoadingStarted 與 onLoadingComplete 的加載監聽回呼。
圖片資源非 null 的情況,就是使用緩存的思路:先從緩存讀取,命中則直接使用,否則下載新資源並進行緩存:
// 1. 對緩存進行一些配置 ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize()); String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize); engine.prepareDisplayTaskFor(imageAware, memoryCacheKey); // 2. 開始加載監聽 listener.onLoadingStarted(uri, imageAware.getWrappedView()); // 3. 從內存緩存獲取 Bitmap Bitmap bmp = configuration.memoryCache.get(memoryCacheKey); if (bmp != null && !bmp.isRecycled()) { // 緩存存在 if (options.shouldPostProcess()) { ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, engine.getLockForUri(uri)); ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo, defineHandler(options)); 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); } ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, engine.getLockForUri(uri)); LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo, defineHandler(options)); if (options.isSyncLoading()) { displayTask.run(); } else { engine.submit(displayTask); } }
總結本篇要點:
1)使用時先透過 Builder 模式構建 ImageLoaderConfiguration 物件;
2)透過 Builder 模式逐步創建 DisplayImageOptions 物件;
3)透過 ImageLoader 的 init 方法把 ImageLoaderConfiguration 與 ImageLoader 關聯起來,也連帶關聯了 DisplayImageOptions;
4)透過 displayImage 重載方法,結合上述兩者完成對 ImageView 的圖片展示。

以上就是 ImageLoader 從初始化到圖片加載的整體流程梳理,如有不當之處,歡迎批評指正,共同學習和進步。
Android 安卓 VPN 設置 L2TP 圖解教學
以下以圖文步驟教學如何在 Android 手機上設置 L2TP/IPSec PSK 類型的 VPN。 第一步:打開手機主選單,選擇「設定」,然後選擇「無線和網絡」。 第
Android 為何 getWidth() 與 getHeight() 會是 0?
問題描述 在 Activity 的 onCreate 或 onResume 中直接呼叫 ImageView 的 getWidth() 與 getHeight(),常常會得
自定義 View 系列(1):仿支付寶物流狀態進度條
照國際慣例,先上支付寶裡的原始效果圖: 再來一張自定義 View 的效果圖: 對比這兩張圖,可能有人會問:物流狀態被選中時的背景怎麼不見了?其實是有的,只是我把那幾行
打造炫目圓形菜單,輕鬆高仿建行圓形菜單
一、概述 今天打開建行 App 看存款,一看悲從中來;再一看:欸,這個圓形菜單挺炫的。於是為了排遣悲痛,我決定親手實現一次這個效果。當然還有另一個原因——當初剛學 And