編輯:關於 Android 程式設計
Android-Universal-Image-Loader 是 GitHub 上一個廣受歡迎的開源圖片加載框架,它同時提供了 MemoryCache(內存緩存)與 DiskCache(磁盤緩存)雙重機制,並支持從網絡、本地文件、ContentProvider 等多種來源加載圖片。
"https://site.com/image.png" // 來自網絡 "file:///mnt/sdcard/image.png" // 來自 SD 卡 "file:///mnt/sdcard/video.mp4" // 來自 SD 卡(視頻縮略圖) "content://media/external/images/media/13" // 來自 content provider "content://media/external/video/media/13" // 來自 content provider(視頻縮略圖) "assets://image.png" // 來自 assets "drawable://" + R.drawable.img // 來自 drawables(非 9-patch 圖片,一般不建議使用)
NOTE:只有在確有必要時才用 drawable://,加載 drawable 首選原生的 ImageView.setImageResource(...),而非繞道 ImageLoader。
ImageLoader imageLoader = ImageLoader.getInstance();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader.init(config);
imageLoader.displayImage("https://pic32.nipic.com/20130829/12906030_124355855000_2.png", image);
第一行以單例模式拿到 ImageLoader 實例;接著必須構造 ImageLoaderConfiguration 並完成初始化,否則運行時會拋出異常。
這個配置類幾乎涵蓋了框架的所有可調參數:
final Resources resources; //加載 app 資源文件 final int maxImageWidthForMemoryCache; //內存緩存圖片寬度最大值,默認為屏幕寬度 final int maxImageHeightForMemoryCache; //同上 final int maxImageWidthForDiskCache; //磁盤緩存寬度,默認無限制 final int maxImageHeightForDiskCache; //同上 final BitmapProcessor processorForDiskCache; //磁盤緩存位圖處理器 final Executor taskExecutor; //任務執行者 final Executor taskExecutorForCachedImages; //緩存圖片任務執行者 final int threadPoolSize; //線程池大小,默認為3 final int threadPriority; //線程優先級 final QueueProcessingType tasksProcessingType; //隊列類型 FIFO / LIFO final MemoryCache memoryCache; //內存緩存 final DiskCache diskCache; //磁盤緩存 final ImageDownloader downloader; //圖片下載器 final ImageDecoder decoder; //圖片解碼器 final DisplayImageOptions defaultDisplayImageOptions; //圖片展示選項 final ImageDownloader networkDeniedDownloader; //離線圖片下載器 final ImageDownloader slowNetworkDownloader; //網速慢圖片下載器
下面是一份帶默認值的完整配置示範,你可以按需增刪:
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // 默認 = 屏幕尺寸
.diskCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)
.threadPoolSize(3) // 默認
.threadPriority(Thread.NORM_PRIORITY - 1) // 默認
.tasksProcessingOrder(QueueProcessingType.FIFO) // 默認
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // 默認
.diskCache(new UnlimitedDiscCache(cacheDir)) // 默認
.diskCacheSize(50 * 1024 * 1024)
.diskCacheFileCount(100)
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // 默認
.imageDownloader(new BaseImageDownloader(context)) // 默認
.imageDecoder(new BaseImageDecoder()) // 默認
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // 默認
.writeDebugLogs()
.build();

根據需求挑選合適的 disk 與 memory 緩存策略即可。
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;
} else {
L.w(WARNING_RE_INIT_CONFIG);
}
}
init 方法接收配置信息,並據此初始化 ImageLoaderEngine 引擎(核心是把各類 TaskExecutor 準備好)。
參數最全的重載版本如下,涵蓋圖片 uri、圖片控件、展示選項、目標尺寸、加載監聽與進度監聽:
public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageSize targetSize, ImageLoadingListener listener, ImageLoadingProgressListener progressListener)
方法開頭先做一些防護性判斷:
checkConfiguration(); // 檢查是否已初始化
if (imageAware == null) { throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS); }
if (listener == null) { listener = defaultListener; }
if (options == null) { options = configuration.defaultDisplayImageOptions; }
接著處理 uri 為空的邊界情況——直接取消任務、回調開始與完成,並按需設置佔位圖,然後 return,這種情況無需緩存:
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;
}
if (targetSize == null) {
targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());
}
若未指定目標尺寸,則依據控件自身大小推算:
public static ImageSize defineTargetSizeForView(ImageAware imageAware, ImageSize maxImageSize) {
int width = imageAware.getWidth();
if (width <= 0) width = maxImageSize.getWidth();
int height = imageAware.getHeight();
if (height <= 0) height = maxImageSize.getHeight();
return new ImageSize(width, height);
}
隨後根據 uri 與目標尺寸生成內存緩存 key,把任務登記到 engine,並回調 started:
String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize); engine.prepareDisplayTaskFor(imageAware, memoryCacheKey); listener.onLoadingStarted(uri, imageAware.getWrappedView());
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);
}
}
命中且未回收時最省事:若配置了 postProcess 就先處理再展示,否則直接交給 displayer 顯示並回調 complete。displayer 可以設置淡入、圓角等效果,最樸素的實現只有一句:
public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {
imageAware.setImageBitmap(bitmap);
}
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); }
}
沒有緩存就得老老實實從原始來源加載:先取圖,再寫入磁盤與內存,最後展示。LoadAndDisplayImageTask 的 run 方法開頭通過一把鎖避免重複加載:
if (waitIfPaused()) return; if (delayIfNeed()) return; ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock; loadFromUriLock.lock();
這把鎖的意義在於:當 ListView 裡某個 item 因快速滑動被反覆移出、移入時,相同 URL 的請求會在 lock 處排隊等待,等前一次加載完成釋放鎖後再繼續,從根本上杜絕了對同一圖片的重複網絡請求。
Bitmap bmp;
try {
checkTaskNotActual();
bmp = configuration.memoryCache.get(memoryCacheKey);
if (bmp == null || bmp.isRecycled()) {
bmp = tryLoadBitmap();
if (bmp == null) return;
checkTaskNotActual();
checkTaskInterrupted();
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); }
} catch (TaskCancelledException e) {
fireCancelEvent(); return;
} finally {
loadFromUriLock.unlock();
}
DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
runTask(displayBitmapTask, syncLoading, handler, engine);
private Bitmap tryLoadBitmap() throws TaskCancelledException {
Bitmap bitmap = null;
try {
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);
}
}
} catch (IllegalStateException e) { fireFailEvent(FailType.NETWORK_DENIED, null); }
catch (IOException e) { fireFailEvent(FailType.IO_ERROR, e); }
catch (OutOfMemoryError e) { fireFailEvent(FailType.OUT_OF_MEMORY, e); }
catch (Throwable e) { fireFailEvent(FailType.UNKNOWN, e); }
return bitmap;
}
而 tryCacheImageOnDisk 負責在磁盤未命中時從網絡下載並落盤:
private boolean tryCacheImageOnDisk() throws TaskCancelledException {
boolean loaded;
try {
loaded = downloadImage();
if (loaded) {
int width = configuration.maxImageWidthForDiskCache;
int height = configuration.maxImageHeightForDiskCache;
if (width > 0 || height > 0) { resizeAndSaveImage(width, height); }
}
} catch (IOException e) { loaded = false; }
return loaded;
}
private boolean downloadImage() throws IOException {
InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
if (is == null) { return false; }
try { return configuration.diskCache.save(uri, is, this); }
finally { IoUtils.closeSilently(is); }
}
至此,一張圖片從「內存 → 磁盤 → 網絡」三級遞歸的緩存與展示旅程就完整閉環了。理解了這套流程,你就能輕鬆定制屬於自己的加載策略。
Android 小遊戲實作:成語猜謎關卡設計與資料讀取
遊戲目標這個小遊戲以成語猜謎為主題,玩家需要根據題目提供的成語解釋,從四個選項中選出正確答案。每局最多十題,答對六題即可視為闖關成功。頁面結構GameActivity:遊
自定義 View 系列(1):仿支付寶物流狀態進度條
照國際慣例,先上支付寶裡的原始效果圖: 再來一張自定義 View 的效果圖: 對比這兩張圖,可能有人會問:物流狀態被選中時的背景怎麼不見了?其實是有的,只是我把那幾行
Android自訂WaveView與流量波形介面分享
本文分享兩種Android波形效果:一種是由中心向外擴散的漣漪動畫,另一種是上下起伏的流量波形。RippleView:同心圓擴散RippleView透過Canvas繪製多
Android 4.4.2 源碼分析之 WiFi 模組(一)
已經寫過幾篇關於 Android 源碼的文章。由於源碼量龐大,想分析某個模組時往往不知從何下手,這裡先分享一套思路: 1. 分析源碼需要一定的英文閱讀能力,通常直接以模組