Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android-Universal-Image-Loader 源碼解析:一張圖片的完整載入與雙層快取旅程

編輯:關於 Android 開發

Android-Universal-Image-Loader(簡稱 UIL)是 GitHub 上相當知名的開源圖片快取框架,提供 MemoryCache 與 DiskCache 兩層機制,並支援載入網路、本機與 ContentProvider 的圖片。本文直接從源碼切入,追一次 displayImage 的完整流程。

支援的 URI 形式

"https://site.com/image.png" // 網路
"file:///mnt/sdcard/image.png" // SD 卡
"file:///mnt/sdcard/video.mp4" // SD 卡影片縮圖
"content://media/external/images/media/13" // ContentProvider
"content://media/external/video/media/13" // ContentProvider 影片縮圖
"assets://image.png" // assets
"drawable://" + R.drawable.img // 非 9-patch 的 drawable,通常不建議使用

官方特別提醒: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 做初始化,否則會直接拋出例外。

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 boolean customExecutor;
final boolean customExecutorForCachedImages;
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)
    .taskExecutor(...)
    .taskExecutorForCachedImages(...)
    .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();

可依需求挑選磁碟與記憶體的快取策略。

init:把配置交給引擎

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);
    }
}

init 接收配置,並據此建立 ImageLoaderEngine(主要工作是初始化其中的 TaskExecutor)。重複初始化只會印出警告,不會覆寫既有設定。

displayImage:流程拆解

參數最完整的重載版本是:

public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageSize targetSize, ImageLoadingListener listener, ImageLoadingProgressListener progressListener)

參數依序為圖片 URI、圖片容器、展示選項、目標尺寸、載入監聽器與進度監聽器;options 裡還有更多細項可調。

第一步:前置檢查與預設值填補

checkConfiguration();
if (imageAware == null) throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
if (listener == null) listener = defaultListener;
if (options == null) options = configuration.defaultDisplayImageOptions;

checkConfiguration 就是確認 configuration 不為 null,否則丟出 IllegalStateException。

第二步:URI 為空的處理

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());
}

URI 為空時直接取消任務、觸發 started 與 complete 回呼,然後 return——這種情況不需要快取,也沒什麼好處理的。若未指定目標尺寸,則依容器實際大小推算:

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);
}

第三步:註冊任務並查記憶體快取

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);
    }
}

key 由 URI 加上目標尺寸組合而成,任務先放進 engine 的集合中,再觸發 started 回呼。接著從記憶體快取取出 bitmap:若存在且未被回收,路徑就很單純——需要前處理時交給 ProcessAndDisplayImageTask 封裝處理後再展示;不需要時直接呼叫 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);
}

這時流程變複雜:先從原始來源載入圖片,寫入磁碟與記憶體,最後才展示。是否同步執行由 options.isSyncLoading() 決定,非同步時交給 engine 內的 Executor(線程池)處理。

LoadAndDisplayImageTask.run:鎖與快取的關鍵

if (waitIfPaused()) return;
if (delayIfNeed()) return;
ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);
if (loadFromUriLock.isLocked()) L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);
loadFromUriLock.lock();

前兩行是中斷與延時判斷,回傳 true 就直接退出。第四行取得鎖並上鎖,目的是防止重複載入。

這個設計值得細看:假設某個 ListView item 正在抓圖,使用者把它滑出畫面又滑回來,若沒有鎖,這個 item 會再抓一次;短時間內頻繁滑動,就會對同一個 URL 發出大量請求。UIL 的做法是為每個 URL 配一把 ReentrantLock,相同 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) L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
        }
        if (bmp != null && options.isCacheInMemory()) {
            configuration.memoryCache.put(memoryCacheKey, bmp);
        }
    } else {
        loadedFrom = LoadedFrom.MEMORY_CACHE;
        L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);
    }
    if (bmp != null && options.shouldPostProcess()) {
        bmp = options.getPostProcessor().process(bmp);
        if (bmp == null) L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);
    }
    checkTaskNotActual();
    checkTaskInterrupted();
} catch (TaskCancelledException e) {
    fireCancelEvent();
    return;
} finally {
    loadFromUriLock.unlock();
}
DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
runTask(displayBitmapTask, syncLoading, handler, engine);

拿到鎖之後再查一次記憶體——因為等待期間可能已經有其他線程把圖片快取進來了。若仍沒有,就呼叫 tryLoadBitmap,成功後依設定做前處理、寫入記憶體快取,最後做後處理,並在 finally 中釋放鎖。進度回呼在從網路取圖時觸發,onStart 則在最開始就觸發了。

tryLoadBitmap:磁碟優先,網路墊後

private Bitmap tryLoadBitmap() throws TaskCancelledException {
    Bitmap bitmap = null;
    try {
        File imageFile = configuration.diskCache.get(uri);
        if (imageFile != null && imageFile.exists() && imageFile.length() > 0) {
            L.d(LOG_LOAD_IMAGE_FROM_DISK_CACHE, memoryCacheKey);
            loadedFrom = LoadedFrom.DISC_CACHE;
            checkTaskNotActual();
            bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));
        }
        if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
            L.d(LOG_LOAD_IMAGE_FROM_NETWORK, memoryCacheKey);
            loadedFrom = LoadedFrom.NETWORK;
            String imageUriForDecoding = uri;
            if (options.isCacheOnDisk() && tryCacheImageOnDisk()) {
                imageFile = configuration.diskCache.get(uri);
                if (imageFile != null) {
                    imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath());
                }
            }
            checkTaskNotActual();
            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 (TaskCancelledException e) {
        throw e;
    } catch (IOException e) {
        L.e(e); fireFailEvent(FailType.IO_ERROR, e);
    } catch (OutOfMemoryError e) {
        L.e(e); fireFailEvent(FailType.OUT_OF_MEMORY, e);
    } catch (Throwable e) {
        L.e(e); fireFailEvent(FailType.UNKNOWN, e);
    }
    return bitmap;
}

策略很清楚:先讀磁碟快取,讀不到才走網路。異常處理也分得很細,網路被禁用、IO 錯誤、記憶體不足、未知錯誤各有對應的 FailType,方便呼叫端決定顯示哪張佔位圖。

tryCacheImageOnDisk 的職責是在磁碟未命中時從網路取圖並落地:

private boolean tryCacheImageOnDisk() throws TaskCancelledException {
    L.d(LOG_CACHE_IMAGE_ON_DISK, memoryCacheKey);
    boolean loaded;
    try {
        loaded = downloadImage();
        if (loaded) {
            int width = configuration.maxImageWidthForDiskCache;
            int height = configuration.maxImageHeightForDiskCache;
            if (width > 0 || height > 0) {
                L.d(LOG_RESIZE_CACHED_IMAGE_FILE, memoryCacheKey);
                resizeAndSaveImage(width, height);
            }
        }
    } catch (IOException e) {
        L.e(e);
        loaded = false;
    }
    return loaded;
}

private boolean downloadImage() throws IOException {
    InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
    if (is == null) {
        L.e(ERROR_NO_IMAGE_STREAM, memoryCacheKey);
        return false;
    } else {
        try {
            return configuration.diskCache.save(uri, is, this);
        } finally {
            IoUtils.closeSilently(is);
        }
    }
}

下載完成後若設定了磁碟快取尺寸上限,還會順手做縮圖再存檔。至此,一張圖片從網路到記憶體、磁碟,再到畫面上的完整旅程就走完了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved