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

Universal-Image-Loader 原始碼全解析(三):displayImage 到底做了什麼

編輯:關於 Android 程式設計

這一篇要從原始碼的角度把這個強大的圖片加載框架拆開來看。上一篇寫完到現在隔了三個月,換了工作要消化的東西不少,加上自己也偷懶,熱情確實退了一些。不過好記性不如爛筆頭,翻回自己以前寫的東西,總比讓知識留在腦海裡可靠。建議先讀過前面兩篇——基本介紹及使用與圖片緩存策略詳解——再往下看,收穫會更紮實。

先回到最熟悉的使用場景:

ImageView mImageView = (ImageView) findViewById(R.id.image);
String imageUrl = "https://lh6.googleusercontent.com/.../A%20Photographer.jpg";

DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_stub)
        .showImageOnFail(R.drawable.ic_error)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .bitmapConfig(Bitmap.Config.RGB_565)
        .build();

ImageLoader.getInstance().displayImage(imageUrl, mImageView, options);

進入 displayImage 的公有入口:

public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {
    displayImage(uri, new ImageViewAware(imageView), options, null, null);
}

第一步是把 ImageView 包裝成 ImageViewAware。這個類做兩件事:把 ImageView 的強引用換成弱引用,讓記憶體吃緊時能被順利回收;以及提供取得 ImageView 寬高的能力,讓框架能依實際尺寸裁切圖片,省下可觀的記憶體。

displayImage 的前置處理

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

第一行檢查 ImageLoaderConfiguration 是否已初始化,這一步通常在 Application 中完成。

中段這一大塊處理的是 uri 為空的情況:先取消該 ImageView 上可能殘留的任務,然後在 ImageLoaderEngine 內部那個用來記錄「正在加載的任務」的 HashMap 裡登記本次請求(key 由 view id 加上 url 與尺寸組成),接著把 options 中為空 uri 準備的佔位圖交給 ImageView,最後回呼 ImageLoadingListener 告知任務結束。這個 HashMap 的機制很關鍵,後面談重複請求時還會再遇到。

先查記憶體快取

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

第一行把 ImageView 的尺寸封裝成 ImageSize。若取到的寬高為 0,就退回使用螢幕尺寸。這解釋了一個常見現象:在 ListView、GridView 中,第一頁因為 item 尚未完成 layout 而取到 0,所以用的是螢幕寬高,後續頁面拿到的才是控件本身的尺寸。

接著以 memoryCacheKey 查記憶體快取,預設實作是 LruMemoryCache。

第 11 行的判斷是:如果 options 設定了 postProcessor 就走一條路,否則走另一條。預設 postProcessor 為 null。BitmapProcessor 這個介面框架本身沒有提供實作,留給使用者自行擴充,例如把圖片處理成圓形。

最後兩行是把 Bitmap 交給 displayer 顯示。預設是 SimpleBitmapDisplayer,直接把 Bitmap 設到 ImageView 上;框架另外提供了 FadeInBitmapDisplayer(透明度 0 到 1 漸入)與 RoundedBitmapDisplayer(四角圓弧)等實作,顯示完成後同樣回呼 listener。

快取未命中:建立載入任務

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。它實作了 Runnable:isSyncLoading 為 true 時直接同步跑 run(),預設 false,交給執行緒池處理。

LoadAndDisplayImageTask.run() 的開場兩道關卡

if (waitIfPaused()) return;
if (delayIfNeed()) return;

任一關卡回傳 true,run() 就直接結束。先看 waitIfPaused():

private boolean waitIfPaused() {
    AtomicBoolean pause = engine.getPause();
    if (pause.get()) {
        synchronized (engine.getPauseLock()) {
            if (pause.get()) {
                L.d(LOG_WAITING_FOR_RESUME, memoryCacheKey);
                try {
                    engine.getPauseLock().wait();
                } catch (InterruptedException e) {
                    L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
                    return true;
                }
                L.d(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);
            }
        }
    }
    return isTaskNotActual();
}

這個設計是為了解決滑動流暢度問題。在 ListView、GridView 中滑動時,我們往往不希望圖片加載搶佔資源,於是提供 PauseOnScrollListener 讓框架在滑動期間暫停。用法很簡單:listView.setOnScrollListener(new PauseOnScrollListener(pauseOnScroll, pauseOnFling)),其中 pauseOnScroll 控制緩慢滑動時是否暫停,pauseOnFling 控制快速 fling 時是否暫停。

方法的返回值則由 isTaskNotActual() 決定:

private boolean isTaskNotActual() {
    return isViewCollected() || isViewReused();
}

isViewCollected() 判斷 ImageView 是否已被回收,若是則 run() 直接返回。isViewReused() 判斷該 ImageView 是否已被複用——ListView、GridView 會重用 item,如果第一頁圖片還沒載完使用者就快速滾動,這個判斷能避免不可見的 item 繼續發出請求,把資源留給當前可見的畫面。

以 URL 為粒度的鎖

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

這把鎖從 ImageLoaderEngine 的 getLockForUri() 取得:

ReentrantLock getLockForUri(String uri) {
    ReentrantLock lock = uriLocks.get(uri);
    if (lock == null) {
        lock = new ReentrantLock();
        uriLocks.put(uri, lock);
    }
    return lock;
}

也就是說,鎖與圖片 URL 是一一對應的。為什麼要這麼設計?想一個場景:ListView 中某個 item 正在載圖,你把它滾出畫面又滾回來。如果沒有鎖,這個 item 會再發一次請求;使用者往復滑動越頻繁,同一張圖的網路請求就可能被重複觸發多次。有了以 URL 為鍵的 ReentrantLock,相同 URL 的請求會在第 7 行排隊等待,等前一次載完釋放鎖後,它們才繼續往下走,並在第 12 行先撈一次記憶體快取——通常這時已經有了,網路請求就避免了。

tryLoadBitmap:先檔案,後網路

File imageFile = configuration.diskCache.get(uri);
if (imageFile != null && imageFile.exists()) {
    L.d(LOG_LOAD_IMAGE_FROM_DISK_CACHE, memoryCacheKey);
    loadedFrom = LoadedFrom.DISC_CACHE;
    checkTaskNotActual();
    bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));
}

先確認檔案快取裡有沒有這個檔案,有的話直接呼叫 decodeImage() 解碼。該方法內部走 BaseImageDecoder 的 decode(),會依 ImageView 的寬高與 ScaleType 做裁切與取樣,細節這裡不展開,有興趣可以自行翻閱。

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

檔案快取撈不到、或解出來寬高為 0,就轉往網路。第 6 行檢查 isCacheOnDisk——注意這個選項預設是 false,實務上通常要手動打開。接著 tryCacheImageOnDisk() 會把圖片拉回來並落地存檔。

private Bitmap decodeImage(String imageUri) throws IOException {
    ViewScaleType viewScaleType = imageAware.getScaleType();
    ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey, imageUri, uri,
            targetSize, viewScaleType, getDownloader(), options);
    return decoder.decode(decodingInfo);
}

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) {
                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());
    return configuration.diskCache.save(uri, is, this);
}

downloadImage() 負責下載並寫入檔案快取,同時把進度回呼到 CopyListener 的 onBytesCopied(current, total),所以只要設定 ImageLoadingProgressListener 就能拿到下載進度。此時存進檔案系統的是原圖。

後面那段是很多人問過的問題:既然存的是原圖,怎麼讓快取裡放縮圖?答案就在 maxImageWidthForDiskCache 與 maxImageHeightForDiskCache。在 Application 建立 ImageLoaderConfiguration 時設定這兩個值,框架就會呼叫 resizeAndSaveImage() 裁切後覆蓋原本的檔案。

if (bmp == null) return;
checkTaskNotActual();
checkTaskInterrupted();
if (options.shouldPreProcess()) {
    bmp = options.getPreProcessor().process(bmp);
}
if (bmp != null && options.isCacheInMemory()) {
    configuration.memoryCache.put(memoryCacheKey, bmp);
}

這段就單純了:按需做前處理,然後寫入記憶體快取。

最後一步:顯示

DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
runTask(displayBitmapTask, syncLoading, handler, engine);
@Override
public void run() {
    if (imageAware.isCollected()) {
        listener.onLoadingCancelled(imageUri, imageAware.getWrappedView());
    } else if (isViewWasReused()) {
        listener.onLoadingCancelled(imageUri, imageAware.getWrappedView());
    } else {
        displayer.display(bitmap, imageAware, loadedFrom);
        engine.cancelDisplayTaskFor(imageAware);
        listener.onLoadingComplete(imageUri, imageAware.getWrappedView(), bitmap);
    }
}

DisplayBitmapTask 在真正畫上去之前又做了一次「視圖是否還活著、是否已被複用」的複查,這道防線很重要:圖片載完往往已經過了一段時間,其間 ImageView 可能早就被回收或改作他用。若無效就走取消回呼,否則交給 displayer 呈現,並把該 view 從任務表中摘除。

把整條鏈路串起來看:displayImage 先做參數校驗與空 uri 處理,接著以「uri 加尺寸」為 key 撈記憶體快取;未命中就建立 LoadAndDisplayImageTask 丟進執行緒池,任務開跑前先通過暫停與複用兩道關卡,再以 URL 粒度的 ReentrantLock 消除重複請求,依序嘗試檔案快取與網路,中間穿插前處理、後處理與兩級快取寫入,最後由 DisplayBitmapTask 複查有效性後呈現。

這個框架之所以好讀也好改,是因為它把每個環節都抽成了可替換的介面:Downloader、DiskCache、MemoryCache、Decoder、Displayer、PreProcessor、PostProcessor。設計上大量使用建造者模式、裝飾模式、代理模式與策略模式,讓擴充變成實作一個介面的事。理解這條主幹之後,要換掉其中任一環節都不難。

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