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

ImageLoader 源碼剖析(三):磁盤緩存與網絡加載全鏈路

編輯:關於 Android 程式設計

緩存的原理說穿了並不複雜:先從網絡拉取資源,用內存緩存或磁盤緩存把它存下來;再次請求同一資源時,若緩存仍在就直接取用,否則重新走網絡。真正有價值的收穫不在結論,而在閱讀源碼的過程中——看別人如何設計類與接口、如何組織異步加載機制,再挑選能借鑒的部分用到自己的項目裡。

上一篇分析了從讀取內存到最終顯示圖片的流程,結論是無論異步還是同步,最終都會落到 ImageView 的 setImageBitmap 或 setImageDrawable。本文接着往下走,看內存緩存未命中之後發生的事。

一、內存未命中時的入口

// 加載過程中先顯示一張佔位圖
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);
}

這段代碼做了兩件事。第一,在真正加載開始前顯示一張佔位圖,避免用戶在等待期間看到一片空白——前提是創建 DisplayImageOptions 時調用了 showImageOnLoading(Drawable)。第二,把圖片地址、目標尺寸、監聽器與配置封裝成 LoadAndDisplayImageTask,這個類是個 Runnable,顧名思義負責「加載並顯示」;同步模式下直接 run,否則交給 engine 的異步機制調度。

二、run 方法中的緩存與後處理

// 先再確認一次內存緩存
bmp = configuration.memoryCache.get(memoryCacheKey);
if (bmp == null || bmp.isRecycled()) {
    bmp = tryLoadBitmap();          // 從文件緩存或網絡加載
    if (bmp == null) return;

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

DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
runTask(displayBitmapTask, syncLoading, handler, engine);

由此可以整理出四點結論:

1)從文件緩存或網絡取得的 Bitmap,在放入內存緩存之前,若 Options 配置了 preProcessor,會先經過一次加工;
2)若 Options 允許內存緩存,加工後的 bitmap 會被放入 memory cache;
3)若還需要顯示階段的處理,則配置 postProcessor;
4)最終仍舊由 DisplayBitmapTask 完成顯示。

有人會問:這裡並沒有看到讀文件或發網絡請求的代碼。它們都藏在 tryLoadBitmap() 裡。

三、tryLoadBitmap:磁盤緩存優先,網絡兜底

private Bitmap tryLoadBitmap() throws TaskCancelledException {
    Bitmap bitmap = null;

    // 1) 先讀文件緩存
    File imageFile = cache.get(uri);
    if (imageFile != null && imageFile.exists()) {
        loadedFrom = LoadedFrom.DISC_CACHE;
        bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));
    }

    // 2) 失敗或尺寸異常則走網絡
    if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
        loadedFrom = LoadedFrom.NETWORK;
        String imageUriForDecoding = uri;
        if (options.isCacheOnDisk() && tryCacheImageOnDisk()) {
            imageFile = cache.get(uri);
            if (imageFile != null) {
                imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath());
            }
        }
        bitmap = decodeImage(imageUriForDecoding);
    }
    return bitmap;
}

值得留意的是中間那段判斷,它實際做了四件事:

1)定義 imageUriForDecoding,初值為原始 uri;
2)若 Options 允許文件緩存,調用 tryCacheImageOnDisk() 下載並保存,成功後把解碼地址改為本地文件路徑;
3)若不容許緩存或保存失敗,imageUriForDecoding 仍等於原始 uri,即直接從網絡流解碼;
4)最後統一調用 decodeImage 生成 bitmap。

四、decodeImage 的內部實現

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

它把參數打包成 ImageDecodingInfo,交給 decoder 處理。decoder 是 ImageDecoder 接口的實現,在 LoadAndDisplayImageTask 構造時從配置中取出:

public LoadAndDisplayImageTask(ImageLoaderEngine engine, ImageLoadingInfo imageLoadingInfo, Handler handler) {
    decoder = configuration.decoder;
}

而 ImageLoaderConfiguration 由 Builder 逐步構建。由於實踐中幾乎沒人顯式配置 decoder,Builder 必然提供了默認值——在 initEmptyFieldsWithDefaultValues() 中可以找到:

if (decoder == null) {
    decoder = DefaultConfigurationFactory.createImageDecoder(writeLogs);
}

public static ImageDecoder createImageDecoder(boolean loggingEnabled) {
    return new BaseImageDecoder(loggingEnabled);
}

於是目標明確:BaseImageDecoder.decode()。

public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException {
    InputStream imageStream = getImageStream(decodingInfo);
    try {
        ImageFileInfo imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
        imageStream = resetStream(imageStream, decodingInfo);
        Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo);
        decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions);
    } finally {
        IoUtils.closeSilently(imageStream);
    }

    if (decodedBitmap == null) {
        // 解碼失敗處理
    } else {
        decodedBitmap = considerExactScaleAndOrientatiton(decodedBitmap, decodingInfo,
                imageInfo.exif.rotation, imageInfo.exif.flipHorizontal);
    }
    return decodedBitmap;
}

方法本身不算長,但內部來回調用的環節不少,這裡不逐一展開。

五、文件緩存的落地過程

private boolean tryCacheImageOnDisk() throws TaskCancelledException {
    boolean loaded = downloadImage();
    if (loaded) {
        int width = configuration.maxImageWidthForDiskCache;
        int height = configuration.maxImageHeightForDiskCache;
        if (width > 0 || height > 0) {
            resizeAndSaveImage(width, height);   // 縮放後重新保存
        }
    }
    return loaded;
}

private boolean downloadImage() throws IOException {
    InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
    return cache.save(uri, is, this);
}

cache 的來源同樣在 Builder 中確定:

if (diskCache == null) {
    if (diskCacheFileNameGenerator == null) {
        diskCacheFileNameGenerator = DefaultConfigurationFactory.createFileNameGenerator();
    }
    diskCache = DefaultConfigurationFactory.createDiskCache(context,
            diskCacheFileNameGenerator, diskCacheSize, diskCacheFileCount);
}

createDiskCache 最終產出的是 UnlimitedDiscCache 對象,它是 BaseDiscCache 的子類且沒有重寫 save,因此看父類即可:

public boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException {
    File imageFile = getFile(imageUri);
    File tmpFile = new File(imageFile.getAbsolutePath() + TEMP_IMAGE_POSTFIX);
    boolean loaded = false;
    OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile), bufferSize);
    loaded = IoUtils.copyStream(imageStream, os, listener, bufferSize);
    return loaded;
}

若配置了 diskCache 的最大寬高,則還會走縮放後重新保存的路徑:

private boolean resizeAndSaveImage(int maxWidth, int maxHeight) throws IOException {
    boolean saved = false;
    File targetFile = cache.get(uri);
    if (targetFile != null && targetFile.exists()) {
        ImageSize targetImageSize = new ImageSize(maxWidth, maxHeight);
        Bitmap bmp = decoder.decode(decodingInfo);
        if (bmp != null && configuration.processorForDiskCache != null) {
            bmp = configuration.processorForDiskCache.process(bmp);
        }
        if (bmp != null) {
            saved = cache.save(uri, bmp);
            bmp.recycle();
        }
    }
    return saved;
}

public boolean save(String imageUri, Bitmap bitmap) throws IOException {
    File imageFile = getFile(imageUri);
    File tmpFile = new File(imageFile.getAbsolutePath() + TEMP_IMAGE_POSTFIX);
    OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile), bufferSize);
    boolean savedSuccessfully = false;
    try {
        savedSuccessfully = bitmap.compress(compressFormat, compressQuality, os);
    } finally {
        bitmap.recycle();
    }
    return savedSuccessfully;
}

有意思的對稱之處是:入內存緩存前可以用 BitmapProcessor 加工,寫磁盤緩存前同樣可以通過 configuration.processorForDiskCache 加工。

六、小結

1)tryLoadBitmap() 從文件緩存或網絡取圖,若需入內存緩存,可先用 BitmapProcessor 加工再放入;
2)disk cache 命中即用,未命中則走網絡;注意若 Options 中未開啟文件緩存,tryCacheImageOnDisk() 根本不會執行,此時行為等同於普通 ImageView 加載網絡圖片,不落盤;
3)tryCacheImageOnDisk() 專職資源的網絡下載與持久化。

篇幅不短,若有理解偏差之處,歡迎指正,共同進步。

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