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

XUtils 源碼細讀:BitmapUtils 的初始化與加載全鏈路

編輯:關於 Android 程式設計

用 XUtils 加載圖片時,調用起來非常簡單——new 一個 BitmapUtils,然後調 display。但這兩行背後其實藏著一整套雙級緩存與異步調度的設計。這篇就沿著源碼把整個流程走一遍。

一、從構造函數說起

BitmapUtils 一共提供了 6 個構造函數,但它們最終都會彙聚到第 2 個(兩個參數的那個):

public BitmapUtils(Context context) {
    this(context, null);
}

public BitmapUtils(Context context, String diskCachePath) {
    if (context == null) {
        throw new IllegalArgumentException("context may not be null");
    }
    this.context = context;
    globalConfig = new BitmapGlobalConfig(context, diskCachePath);
    defaultDisplayConfig = new BitmapDisplayConfig();
}

public BitmapUtils(Context context, String diskCachePath, int memoryCacheSize) {
    this(context, diskCachePath);
    globalConfig.setMemoryCacheSize(memoryCacheSize);
}

public BitmapUtils(Context context, String diskCachePath,
                   int memoryCacheSize, int diskCacheSize) {
    this(context, diskCachePath);
    globalConfig.setMemoryCacheSize(memoryCacheSize);
    globalConfig.setDiskCacheSize(diskCacheSize);
}

public BitmapUtils(Context context, String diskCachePath, float memoryCachePercent) {
    this(context, diskCachePath);
    globalConfig.setMemCacheSizePercent(memoryCachePercent);
}

其餘幾個差別僅在於「是否自定義緩存大小」,參數名已經說明了意圖。真正關鍵的是 BitmapGlobalConfig 的創建。

二、BitmapGlobalConfig:緩存的初始化

public BitmapGlobalConfig(Context context, String diskCachePath) {
    if (context == null)
        throw new IllegalArgumentException("context may not be null");
    this.mContext = context;
    this.diskCachePath = diskCachePath;
    initBitmapCache();
}

前幾行只是判空與賦值,核心在 initBitmapCache():

private void initBitmapCache() {
    new BitmapCacheManagementTask().execute(
            BitmapCacheManagementTask.MESSAGE_INIT_MEMORY_CACHE);
    new BitmapCacheManagementTask().execute(
            BitmapCacheManagementTask.MESSAGE_INIT_DISK_CACHE);
}

這裡用到了 BitmapCacheManagementTask——BitmapGlobalConfig 的私有內部類,繼承自 PriorityAsyncTask。也就是說,內存緩存與磁盤緩存的初始化都是異步完成的。

三、PriorityAsyncTask 的執行鏈

execute 方法在 BitmapCacheManagementTask 中並不存在,需要沿著繼承鏈往上找:

public final PriorityAsyncTask<Params, Progress, Result> execute(Params... params) {
    return executeOnExecutor(sDefaultExecutor, params);
}

public final PriorityAsyncTask<Params, Progress, Result> executeOnExecutor(
        Executor exec, Params... params) {
    return executeOnExecutor(exec, Priority.DEFAULT, params);
}

public final PriorityAsyncTask<Params, Progress, Result> executeOnExecutor(
        Executor exec, Priority priority, Params... params) {
    if (mExecuteInvoked) {
        throw new IllegalStateException("Cannot execute task: the task is already executed.");
    }
    mExecuteInvoked = true;
    onPreExecute();
    mWorker.mParams = params;
    exec.execute(new PriorityRunnable(priority, mFuture));
    return this;
}

整個套路幾乎照搬自 AsyncTask:

  • sDefaultExecutor 是一個 PriorityExecutor 類型的線程池,默認包含 5 個線程。
  • 任務正在執行時再次調用會拋出異常。
  • onPreExecute() 在 PriorityAsyncTask 中是空實現,若想在加載開始前做提示,可以在子類中重寫。
  • 請求參數被交給 WorkerRunnable 類型的 mWorker,它是 AsyncTask 的抽象靜態內部類,實現了 Callable 接口:
mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
        mTaskInvoked.set(true);
        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        return postResult(doInBackground(mParams));
    }
};

接著線程池執行 PriorityRunnable,而它的 run() 其實只是在轉調內部持有的 mFuture:

@Override
public void run() {
    this.obj.run();
}

mFuture 是一個 FutureTask,它的 run() 最終會調用傳入的 Callable(也就是上面的 mWorker)的 call() 方法,於是鏈路回到了 doInBackground()——一個在 PriorityAsyncTask 中同樣抽象的方法,具體實現就在子類 BitmapCacheManagementTask 裡。

追了這麼一圈,結論其實很樸素:BitmapUtils 複用了一套類 AsyncTask 的異步框架,只不過把線程池換成了支持優先級的自定義實現。

四、內存緩存的建立

在 BitmapCacheManagementTask.doInBackground() 中,標記為 MESSAGE_INIT_MEMORY_CACHE 的分支會調用 BitmapCache.initMemoryCache():

public void initMemoryCache() {
    if (!globalConfig.isMemoryCacheEnabled()) return;

    if (mMemoryCache != null) {
        try {
            clearMemoryCache();
        } catch (Throwable e) { }
    }

    mMemoryCache = new LruMemoryCache<MemoryCacheKey, Bitmap>(
            globalConfig.getMemoryCacheSize()) {
        @Override
        protected int sizeOf(MemoryCacheKey key, Bitmap bitmap) {
            if (bitmap == null) return 0;
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    };
}

邏輯很清楚:先判斷是否啟用內存緩存,若已存在則先清空,最後以 globalConfig.getMemoryCacheSize() 為容量創建 LruMemoryCache。值得注意的是重寫的 sizeOf()——它按真實佔用字節數(行字節數 × 高度)計算,而非簡單的對象個數,這樣容量上限才有實際意義。

五、磁盤緩存的建立

標記為 MESSAGE_INIT_DISK_CACHE 的分支調用 BitmapCache.initDiskCache():

public void initDiskCache() {
    if (!globalConfig.isDiskCacheEnabled()) return;

    synchronized (mDiskCacheLock) {
        if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
            File diskCacheDir = new File(globalConfig.getDiskCachePath());
            if (diskCacheDir.exists() || diskCacheDir.mkdirs()) {
                long availableSpace = OtherUtils.getAvailableSpace(diskCacheDir);
                long diskCacheSize = globalConfig.getDiskCacheSize();
                diskCacheSize = availableSpace > diskCacheSize
                        ? diskCacheSize : availableSpace;

                try {
                    mDiskLruCache = LruDiskCache.open(diskCacheDir, 1, 1, diskCacheSize);
                    mDiskLruCache.setFileNameGenerator(globalConfig.getFileNameGenerator());
                } catch (Throwable e) {
                    mDiskLruCache = null;
                    LogUtils.e(e.getMessage(), e);
                }
            }
        }
        isDiskCacheReadied = true;
        mDiskCacheLock.notifyAll();
    }
}

同樣先判斷開關,然後在鎖保護下準備目錄、計算可用空間、取兩者較小值作為緩存上限,最後通過 LruDiskCache.open() 建立對象。注意 isDiskCacheReadied 與 notifyAll()——後續讀取緩存時會 wait() 等待這個標記,這是典型的異步初始化 + 同步屏障組合。

至此,構造階段結束:內存緩存與磁盤緩存都已就緒,BitmapDisplayConfig(用於配置動畫、旋轉等顯示屬性)也已創建。

六、display 方法:四個重載,一條路

public <T extends View> void display(T container, String uri)
public <T extends View> void display(T container, String uri, BitmapDisplayConfig displayConfig)
public <T extends View> void display(T container, String uri, BitmapLoadCallBack<T> callBack)
public <T extends View> void display(T container, String uri,
        BitmapDisplayConfig displayConfig, BitmapLoadCallBack<T> callBack)

前三者都是對第四個的轉調,所以只分析第四個。四個參數的含義:

  • container:要顯示圖片的控件
  • :圖片地址,可以是網絡 URL、本地路徑,或 assets 下的相對路徑
  • displayConfig:顯示配置,如加載中佔位圖、動畫、失敗佔位圖、優先級等
  • callBack:加載過程的回調

回調基類 BitmapLoadCallBack 提供了完整的過程鉤子:

public abstract class BitmapLoadCallBack<T extends View> {
    public void onPreLoad(T container, String uri, BitmapDisplayConfig config) { }
    public void onLoadStarted(T container, String uri, BitmapDisplayConfig config) { }
    public void onLoading(T container, String uri, BitmapDisplayConfig config,
                          long total, long current) { }
    public abstract void onLoadCompleted(T container, String uri, Bitmap bitmap,
                                         BitmapDisplayConfig config, BitmapLoadFrom from);
    public abstract void onLoadFailed(T container, String uri, Drawable drawable);
}

其中 onLoadCompleted 與 onLoadFailed 是必須實現的抽象方法,其餘可按需重寫——例如 onLoading 就非常適合更新進度條。

七、display 的內部流程

public <T extends View> void display(T container, String uri,
        BitmapDisplayConfig displayConfig, BitmapLoadCallBack<T> callBack) {

    if (container == null) {
        return;
    }
    container.clearAnimation();

    if (callBack == null) {
        callBack = new DefaultBitmapLoadCallBack<T>();
    }
    if (displayConfig == null || displayConfig == defaultDisplayConfig) {
        displayConfig = defaultDisplayConfig.cloneNew();
    }

    // 依據 View 尺寸修正圖片最大尺寸,避免不必要的內存浪費
    BitmapSize size = displayConfig.getBitmapMaxSize();
    displayConfig.setBitmapMaxSize(BitmapCommonUtils.optimizeMaxSizeByView(
            container, size.getWidth(), size.getHeight()));

    callBack.onPreLoad(container, uri, displayConfig);

    if (TextUtils.isEmpty(uri)) {
        callBack.onLoadFailed(container, uri, displayConfig.getLoadFailedDrawable());
        return;
    }

    // 1. 先查內存緩存
    Bitmap bitmap = globalConfig.getBitmapCache().getBitmapFromMemCache(uri, displayConfig);
    if (bitmap != null) {
        callBack.onLoadStarted(container, uri, displayConfig);
        callBack.onLoadCompleted(container, uri, bitmap,
                displayConfig, BitmapLoadFrom.MEMORY_CACHE);
    } else if (!bitmapLoadTaskExist(container, uri, callBack)) {
        // 2. 內存沒有,交由異步任務處理
        final BitmapLoadTask<T> loadTask =
                new BitmapLoadTask<T>(container, uri, displayConfig, callBack);

        PriorityExecutor executor = globalConfig.getBitmapLoadExecutor();
        File diskCacheFile = this.getBitmapFileFromDiskCache(uri);
        boolean diskCacheExist = diskCacheFile != null && diskCacheFile.exists();
        if (diskCacheExist && executor.isBusy()) {
            executor = globalConfig.getDiskCacheExecutor();
        }

        // 先展示加載中佔位圖
        Drawable loadingDrawable = displayConfig.getLoadingDrawable();
        callBack.setDrawable(container, new AsyncDrawable<T>(loadingDrawable, loadTask));

        Priority priority = displayConfig.getPriority();
        if (priority == null) {
            priority = Priority.DEFAULT;
        }
        loadTask.executeOnExecutor(executor, priority);
    }
}

逐步拆解關鍵環節:

默認回調。若未傳 callback,會使用 DefaultBitmapLoadCallBack。它的 onLoadCompleted 直接把 Bitmap 設到 container 上,若配置了動畫則通過反射克隆一份 Animation 再 startAnimation(克隆是為了避免同一個動畫對象被多個 View 復用時狀態互相干擾);onLoadFailed 則設置失敗佔位圖。

尺寸優化。optimizeMaxSizeByView() 是這裡最值得欣賞的一段設計:

public static BitmapSize optimizeMaxSizeByView(View view, int maxImageWidth, int maxImageHeight) {
    int width = maxImageWidth;
    int height = maxImageHeight;
    if (width > 0 && height > 0) {
        return new BitmapSize(width, height);   // 已顯式指定,直接返回
    }

    final ViewGroup.LayoutParams params = view.getLayoutParams();
    if (params != null) {
        if (params.width > 0) {
            width = params.width;
        } else if (params.width != ViewGroup.LayoutParams.WRAP_CONTENT) {
            width = view.getWidth();
        }
        if (params.height > 0) {
            height = params.height;
        } else if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
            height = view.getHeight();
        }
    }

    // 仍無法確定時,嘗試讀取 ImageView 的 maxWidth / maxHeight
    if (width <= 0)  width  = getImageViewFieldValue(view, "mMaxWidth");
    if (height <= 0) height = getImageViewFieldValue(view, "mMaxHeight");

    // 最後兜底為屏幕尺寸
    BitmapSize screenSize = getScreenSize(view.getContext());
    if (width <= 0)  width  = screenSize.getWidth();
    if (height <= 0) height = screenSize.getHeight();

    return new BitmapSize(width, height);
}

它的取捨優先級依次是:顯式指定 → LayoutParams 固定值 → View 已測量的實際尺寸 → ImageView 的 max 屬性(通過反射讀取)→ 屏幕尺寸。這樣一張圖被解碼時就不會超出顯示所需的像素量,是內存溢出防護的第一道閘門。

內存緩存命中。getBitmapFromMemCache() 以 uri 為基礎生成 MemoryCacheKey 再查表,命中則同步完成回調,耗時幾乎可忽略。

防止重複任務。bitmapLoadTaskExist() 會檢查該 container 上是否已有加載任務:若舊任務的 uri 與當前一致,返回 true 直接跳過(避免重複請求);若不一致,則先取消舊任務再繼續。這一步是列表快速滑動時避免圖片錯亂的關鍵。

private static <T extends View> boolean bitmapLoadTaskExist(
        T container, String uri, BitmapLoadCallBack<T> callBack) {
    final BitmapLoadTask<T> oldLoadTask = getBitmapTaskFromContainer(container, callBack);
    if (oldLoadTask != null) {
        final String oldUrl = oldLoadTask.uri;
        if (TextUtils.isEmpty(oldUrl) || !oldUrl.equals(uri)) {
            oldLoadTask.cancel(true);
        } else {
            return true;
        }
    }
    return false;
}

最後根據優先級把任務提交給線程池,並在提交前先給控件掛上一個 AsyncDrawable——這正是「加載中佔位圖」的實現方式。

八、doInBackground:磁盤緩存與網絡下載

@Override
protected Bitmap doInBackground(Object... params) {
    synchronized (pauseTaskLock) {
        while (pauseTask && !this.isCancelled()) {
            try {
                pauseTaskLock.wait();
                if (cancelAllTask) return null;
            } catch (Throwable e) { }
        }
    }

    Bitmap bitmap = null;

    if (!this.isCancelled() && this.getTargetContainer() != null) {
        this.publishProgress(PROGRESS_LOAD_STARTED);
        bitmap = globalConfig.getBitmapCache().getBitmapFromDiskCache(uri, displayConfig);
    }

    if (bitmap == null && !this.isCancelled() && this.getTargetContainer() != null) {
        bitmap = globalConfig.getBitmapCache().downloadBitmap(uri, displayConfig, this);
        from = BitmapLoadFrom.URI;
    }

    return bitmap;
}

流程是「暫停檢查 → 查磁盤緩存 → 沒有則下載」。開頭的 pauseTask 循環是 XUtils 的一大特色:列表快速滑動時可以暫停所有加載任務,等滑動停下再批量恢復,避免用戶根本看不見的中間項白白消耗流量。

讀取磁盤緩存時,若命中則通過 BitmapDecoder 解碼(根據配置選擇原圖或降採樣解碼),並順手把結果寫入內存緩存:

private void addBitmapToMemoryCache(String uri, BitmapDisplayConfig config,
        Bitmap bitmap, long expiryTimestamp) throws IOException {
    if (uri != null && bitmap != null
            && globalConfig.isMemoryCacheEnabled() && mMemoryCache != null) {
        MemoryCacheKey key = new MemoryCacheKey(uri, config);
        mMemoryCache.put(key, bitmap, expiryTimestamp);
    }
}

九、downloadBitmap:寫入磁盤緩存再解碼

downloadBitmap() 的策略值得留意:它並不是直接在內存中解碼網絡流,而是優先把數據寫入磁盤緩存,再從磁盤解碼。這樣做的好處是,即使這次解碼失敗或內存緊張,數據已經落地,下次可以直接命中緩存。

真正的網絡讀取在 Downloader.downloadToStream()(默認實現為 DefaultDownloader)中完成,而它同時解釋了「為什麼 BitmapUtils 能同時支持網絡圖、本地圖與 assets 圖」:

if (uri.startsWith("/")) {
    // 本地文件:直接讀取
    FileInputStream fileInputStream = new FileInputStream(uri);
    fileLen = fileInputStream.available();
    bis = new BufferedInputStream(fileInputStream);
    result = System.currentTimeMillis() + this.getDefaultExpiry();
} else if (uri.startsWith("assets/")) {
    // assets:截掉前綴後讀取,過期時間設為 Long.MAX_VALUE
    InputStream inputStream = this.getContext().getAssets()
            .open(uri.substring(7, uri.length()));
    fileLen = inputStream.available();
    bis = new BufferedInputStream(inputStream);
    result = Long.MAX_VALUE;
} else {
    // 網絡:建立連接,設置超時
    final URL url = new URL(uri);
    urlConnection = url.openConnection();
    urlConnection.setConnectTimeout(this.getDefaultConnectTimeout());
    urlConnection.setReadTimeout(this.getDefaultReadTimeout());
    bis = new BufferedInputStream(urlConnection.getInputStream());
    result = urlConnection.getExpiration();
    result = result < System.currentTimeMillis()
            ? System.currentTimeMillis() + this.getDefaultExpiry() : result;
    fileLen = urlConnection.getContentLength();
}

之後是以 4KB 緩衝區循環讀寫,並在每次寫入後調用 task.updateProgress(fileLen, currCount):

byte[] buffer = new byte[4096];
int len = 0;
while ((len = bis.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
    currCount += len;
    if (task.isCancelled() || task.getTargetContainer() == null) return -1;
    task.updateProgress(fileLen, currCount);
}

這條鏈路一路傳下去就是:updateProgress() → publishProgress(PROGRESS_LOADING, ...) → onProgressUpdate() → callBack.onLoading(...)。所以你在 onLoading 中寫的進度條邏輯,數據源正是這裡。

值得稱道的是循環中的 isCancelled() 與 getTargetContainer() == null 判斷:一旦用戶滑走或任務被取消,下載會立刻中止,不再浪費帶寬。

十、結果如何回到界面

異步任務結束後,onPostExecute() 被調用,它負責把結果交回回調:

@Override
protected void onPostExecute(Bitmap bitmap) {
    final T container = this.getTargetContainer();
    if (container != null) {
        if (bitmap != null) {
            callBack.onLoadCompleted(container, this.uri, bitmap, displayConfig, from);
        } else {
            callBack.onLoadFailed(container, this.uri, displayConfig.getLoadFailedDrawable());
        }
    }
}

注意 container != null 這道判斷——它保證了即便 item 早已被回收,也不會出現「圖片設置到已銷毀控件上」的崩潰。而 from 參數會告訴你這張圖來自內存緩存、磁盤緩存還是網絡,可以據此決定是否播放加載動畫。

整體回顧

把整條鏈路串起來:

構造階段:異步初始化 LruMemoryCache 與 LruDiskCache,完成雙級緩存骨架。

display 階段:修正目標尺寸 → 查內存緩存 → 命中即回主線程展示;未命中則檢查重複任務、掛上加載佔位圖、按優先級提交異步任務。

異步階段:查磁盤緩存 → 未命中則下載並落地磁盤 → 解碼 → 回填內存緩存。

回主線程:onPostExecute 判斷 container 有效性後,觸發 onLoadCompleted 或 onLoadFailed。

讀完這條鏈路,你會發現 BitmapUtils 的「簡單兩行調用」背後,其實是尺寸計算、雙級緩存、優先級調度、任務去重、加載暫停、進度回調一整套機制在協同工作。理解它們,不僅能更好地使用 XUtils,遇到加載慢、圖片閃回、內存告急這類問題時,也知道該從哪一層下手排查。

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