編輯:關於 Android 程式設計
在 Android 開發中,圖片顯示幾乎是每個專案都躲不掉的需求。網路上翻資料會發現,Universal Image Loader(以下簡稱 UIL)長期是這個領域的熱門選擇。本文是給初次接觸者的入門導引,同時也是我自己使用這個框架後的一份整理,主要包含:
從用法看,使用這個框架的第一步一定是初始化,通常放在 Application 裡:
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(imageLoaderConfiguration);
跟著原始碼進去看:
private volatile static ImageLoader instance;
/** Returns singleton class instance */
public static ImageLoader getInstance() {
if (instance == null) {
synchronized (ImageLoader.class) {
if (instance == null) {
instance = new ImageLoader();
}
}
}
return instance;
}
protected ImageLoader() { }
/**
* Initializes ImageLoader instance with configuration.
* If configurations was set before ({@link #isInited()} == true) then this method does nothing.
* To force initialization with new configuration you should
* {@linkplain #destroy() destroy ImageLoader} at first.
*/
public synchronized void init(ImageLoaderConfiguration configuration) {
if (configuration == null) {
throw new IllegalArgumentException(ERROR_INIT_CONFIG_WITH_NULL);
}
if (this.configuration == null) {
L.d(LOG_INIT_CONFIG);
engine = new ImageLoaderEngine(configuration);
this.configuration = configuration;
} else {
L.w(WARNING_RE_INIT_CONFIG);
}
}
取得單例用的是經典的 double-checked locking,加上 volatile 修飾,這部分沒什麼特別。值得注意的是 init() 的行為:它只能生效一次,重複呼叫只會印出一行 warning,不會覆寫原本的設定。想換設定必須先 destroy()。
init() 的核心工作就是建立 engine:
engine = new ImageLoaderEngine(configuration);
進到 ImageLoaderEngine 的建構子:
ImageLoaderEngine(ImageLoaderConfiguration configuration) {
this.configuration = configuration;
taskExecutor = configuration.taskExecutor;
taskExecutorForCachedImages = configuration.taskExecutorForCachedImages;
taskDistributor = DefaultConfigurationFactory.createTaskDistributor();
}
結論很清楚:UIL 是透過 Executor 把任務丟進 thread pool 執行的。這裡初始化了三個 Executor 實例——taskExecutor、taskExecutorForCachedImages 與 taskDistributor。把「已命中海內存快取」的任務獨立到另一個 thread pool,是個很值得學的設計,因為快取命中幾乎不耗時,不該和真正的網路/解碼任務排在同一條隊伍裡被拖住。
初始化就聊到這。接著看顯示圖片的方法:
/**
* Adds display image task to execution pool. Image will be set to ImageAware when it's turn.
* NOTE: {@link #init(ImageLoaderConfiguration)} method must be called before this method call
*
* @param uri Image URI (i.e. "https://site.com/image.png", "file:///mnt/sdcard/image.png")
* @param imageAware Image aware view which should display image
* @param options Options for image decoding and displaying.
* If null - default display image options from configuration will be used.
* @param listener Listener for image loading process.
* @param progressListener Listener for image loading progress.
*/
public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,
ImageLoadingListener listener,
ImageLoadingProgressListener progressListener) {
checkConfiguration();
if (imageAware == null) {
throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
}
if (listener == null) {
listener = emptyListener;
}
if (options == null) {
options = configuration.defaultDisplayImageOptions;
}
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;
}
ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware,
configuration.getMaxImageSize());
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()) {
L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);
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);
}
}
}
這段邏輯值得細看,它的分支非常清楚:
MemoryCacheUtils.generateKey),這解釋了為什麼同一張圖在不同尺寸的 ImageView 中會各自快取一份。LoadedFrom.MEMORY_CACHE。shouldShowImageOnLoading),再把 LoadAndDisplayImageTask 丟給 engine 執行。其中這段是我們平時設定的「載入失敗/為空時顯示的圖片」來源:
if (options == null) {
options = configuration.defaultDisplayImageOptions;
}
也就是說,如果呼叫時 options 傳 null,就會退回使用初始化時設定的預設值。
最後由 engine 把任務送出:
engine.submit(displayTask);
submit() 的實作(在 ImageLoaderEngine 中):
/** Submits task to execution pool */
void submit(ProcessAndDisplayImageTask task) {
initExecutorsIfNeed();
taskExecutorForCachedImages.execute(task);
}
private void initExecutorsIfNeed() {
if (!configuration.customExecutor
&& ((ExecutorService) taskExecutor).isShutdown()) {
taskExecutor = createTaskExecutor();
}
if (!configuration.customExecutorForCachedImages
&& ((ExecutorService) taskExecutorForCachedImages).isShutdown()) {
taskExecutorForCachedImages = createTaskExecutor();
}
}
這裡有個很細節的保護:如果 thread pool 已經被 shutdown(例如呼叫過 destroy()),會自動重建,避免拋 RejectedExecutionException。
原始碼就分析到這,想更深入的讀者建議直接翻閱完整實作。接下來進入實作環節。
先取回套件。Gradle 寫法:
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
Maven 寫法:
<dependency>
<groupId>com.nostra13.universalimageloader</groupId>
<artifactId>universal-image-loader</artifactId>
<version>1.9.3</version>
</dependency>
因為涉及圖片快取的讀寫路徑與網路存取,需要在 AndroidManifest.xml 加上權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
接著在 activity_main 放一個顯示圖片的控件:
<ImageView
android:id="@+id/user_image"
android:layout_width="64dp"
android:layout_height="64dp" />
在 MainActivity 中載入一張網路圖片:
imageView = (ImageView) findViewById(R.id.user_image);
ImageLoaderUtil.init(this);
String url_image = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWsK1HF6hhy/it/u=3266622398,4228444443&fm=116&gp=0.jpg";
ImageLoaderUtil.displayImage(url_image, imageView, ImageLoaderUtil.getAvatarDisplayOptions());
顯示效果:

當網路路徑不存在圖片時,會顯示我們設定的預設圖:

其中 ImageLoaderUtil 是我自己封裝的一的工具類,重點在 init():
public static void init(Context context) {
File cacheDir = getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // 記憶體快取的圖片最大寬高,預設為螢幕尺寸
.diskCacheExtraOptions(480, 800, null) // 本地快取的詳細資訊,一般不建议設定
// .taskExecutor("")
// .taskExecutorForCachedImages("")
.threadPoolSize(3) // 線程池內併發載入的數量
.threadPriority(Thread.NORM_PRIORITY - 2)
.tasksProcessingOrder(QueueProcessingType.FIFO)
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 可自訂記憶體快取實作
.memoryCacheSize(2 * 1024 * 1024) // 記憶體快取上限
.memoryCacheSizePercentage(13) // 以百分比方式設定
.diskCache(new UnlimitedDiscCache(cacheDir)) // 可自訂快取路徑
.diskCacheSize(50 * 1024 * 1024) // 本地快取上限 50Mb
.diskCacheFileCount(100) // 快取檔案數量上限
// 預設以 HASHCODE 命名,也可改用 MD5(new Md5FileNameGenerator())
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
.imageDownloader(new BaseImageDownloader(context))
.imageDecoder(new BaseImageDecoder(true))
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.writeDebugLogs() // 印出 debug log
.build();
ImageLoader.getInstance().init(config);
}
完整的工具類:
package constraintlayout.test.test.viviant.imageloadertest.util;
import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import java.io.File;
public class ImageLoaderUtil {
private static final String PICTURE_CACHE_DIR = "picture";
private static final String TAG = "ImageLoaderUtil";
public static void init(Context context) {
File cacheDir = getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800)
.diskCacheExtraOptions(480, 800, null)
.threadPoolSize(3)
.threadPriority(Thread.NORM_PRIORITY - 2)
.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(true))
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
}
/** 取得快取目錄 */
public final static File getCacheDirectory(Context context) {
String cacheDir = SystemUtility.getAppCachePath();
return createDir(cacheDir + PICTURE_CACHE_DIR);
}
private final static File createDir(String dir) {
File appCacheDir = new File(dir);
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdirs()) {
Log.i(TAG, "createDir# Unable to create external cache directory");
return null;
}
}
return appCacheDir;
}
/** 載入中/為空/失敗時的替代圖 */
public static DisplayImageOptions getAvatarDisplayOptions() {
return new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.error)
.showImageForEmptyUri(R.drawable.error)
.showImageOnFail(R.drawable.error)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
}
/** 顯示圖片 */
public static void displayImage(String url, ImageView imageView, DisplayImageOptions options) {
ImageLoader.getInstance().displayImage(url, imageView, options);
}
}
整體來說 UIL 的用法相當直覺:透過 ImageLoaderConfiguration.Builder 設定好快取與線程參數,之後就是一行 displayImage()。它最大的優勢在大量載入網路圖片時的穩定性——雙層快取、可配置線程池、內建的列表滑動優化,這些都省下了自己造輪子的時間。
不過也要客觀說一句:UIL 早已停止維護,新專案建議改用 Glide 或 Fresco 這類仍在活躍維護的方案。讀懂 UIL 的價值,在於它的快取分層與線程池拆分思路,放到今天任何一個圖片框架上都通用。
原始碼下載(Android Studio 可直接匯入):
https://github.com/viviant1224/ImageLoaderTest
以上是我使用這個框架的一些整理,不足之處歡迎指教。
Android 自定義控制項:ToggleButton 開關按鈕
自定義控制項概念自定義 View 可以讓 UI 更靈活。以 ToggleButton 為例,它本質上是一個可在背景圖上滑動的開關,透過繪製與觸摸事件模擬 iOS 風格的切
HTC One X9 一鍵 root 教程:卡刷 SuperSU 包全流程
HTC One X9 的 root 怎麼做?這裡採用的是比較傳統也相對穩定的卡刷方式:透過第三方 Recovery 刷入 zip 格式的 root 包。這個方法的成功率通
Android 通訊錄加入歸屬地分組:自建離線號碼資料庫
先前負責的功能之一是為聯絡人加上「歸屬地」與「公司」兩個智慧分組。網路上能查到的實作不少,其中一派是透過 web service 查詢——但把核心功能綁在別人的伺服器上並
View 滑動衝突的成因與兩種解法
所謂 View 的滑動衝突,是指當內外兩層 View 都能滑動時所產生的爭搶。要解決它,得回到 View 的事件分發機制。 滑動衝突主要分為三種場景: 場景一:外部與內