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

Android 原始碼分析:資源載入機制與自製 Resources 物件

編輯:關於 Android 程式設計

轉載請註明出處:https://blog.csdn.net/singwhatiwanna/article/details/23387079(出自 singwhatiwanna 的 CSDN 部落格)

前言

在 Activity 內部存取資源(字串、圖片等)非常簡單:getResources() 拿到 Resources 物件,之後要什麼資源都有。不過本文要談的不是這個用法,而是這套邏輯背後的資源載入機制。

為什麼不同的 Context 拿到的是同一份資源

很明確的一點:不同 Context 取得的資源其實是同一份。取得資源的入口是 context.getResources(),真正的實作在 ContextImpl.getResources()。ContextImpl 中有一個成員 private Resources mResources,就是這個方法的回傳結果,它的賦值為:

mResources = mResourcesManager.getTopLevelResources(mPackageInfo.getResDir(),
        Display.DEFAULT_DISPLAY, null, compatInfo, activityToken);

接著看 ResourcesManager 的 getTopLevelResources()。這個方法的思路是:ResourcesManager 中所有的資源物件都存在一個 ArrayMap 裡,先依當前請求參數查找,找到就直接回傳,找不到才建立一個新物件放進去。

為什麼會需要多個資源物件?原因很單純:res 底下可能存在多個適配不同裝置、不同解析度、不同系統版本的目錄。依 Android 的設計,不同裝置存取同一個應用時,取得的資源可以不同——drawable-hdpi 與 drawable-xhdpi 就是最典型的例子。

public Resources getTopLevelResources(String resDir, int displayId,
        Configuration overrideConfiguration, CompatibilityInfo compatInfo, IBinder token) {
    final float scale = compatInfo.applicationScale;
    ResourcesKey key = new ResourcesKey(resDir, displayId, overrideConfiguration, scale, token);
    Resources r;
    synchronized (this) {
        WeakReference<Resources> wr = mActiveResources.get(key);
        r = wr != null ? wr.get() : null;
        if (r != null && r.getAssets().isUpToDate()) {
            return r;   // 命中快取,直接回傳
        }
    }

    AssetManager assets = new AssetManager();
    if (assets.addAssetPath(resDir) == 0) {
        return null;
    }

    DisplayMetrics dm = getDisplayMetricsLocked(displayId);
    Configuration config;
    boolean isDefaultDisplay = (displayId == Display.DEFAULT_DISPLAY);
    final boolean hasOverrideConfig = key.hasOverrideConfiguration();
    if (!isDefaultDisplay || hasOverrideConfig) {
        config = new Configuration(getConfiguration());
        if (!isDefaultDisplay) {
            applyNonDefaultDisplayMetricsToConfigurationLocked(dm, config);
        }
        if (hasOverrideConfig) {
            config.updateFrom(key.mOverrideConfiguration);
        }
    } else {
        config = getConfiguration();
    }

    r = new Resources(assets, dm, config, compatInfo, token);

    synchronized (this) {
        WeakReference<Resources> wr = mActiveResources.get(key);
        Resources existing = wr != null ? wr.get() : null;
        if (existing != null && existing.getAssets().isUpToDate()) {
            // 在我們解鎖期間已有其他線程建好,直接沿用對方的
            r.getAssets().close();
            return existing;
        }
        mActiveResources.put(key, new WeakReference<Resources>(r));
        return r;
    }
}

再加上 ResourcesManager 採用單例模式,就保證了不同 ContextImpl 存取的是同一套資源:

public static ResourcesManager getInstance() {
    synchronized (ResourcesManager.class) {
        if (sResourcesManager == null) {
            sResourcesManager = new ResourcesManager();
        }
        return sResourcesManager;
    }
}

這裡要說清楚一個細節:同一套資源未必是同一個資源物件,因為資源可能位於不同目錄。更精確的說法是——在裝置參數與顯示參數不變的前提下,不同的 ContextImpl 會存取到同一份資源。裝置參數不變指螢幕與 Android 版本不變,顯示參數不變指解析度與橫豎屏狀態不變。

也就是說,雖然 Application、Activity、Service 各自持有 ContextImpl,每個 ContextImpl 也都有自己的 mResources 成員,但因為它們都來自唯一的 ResourcesManager 實例,所以這些看似不同的 mResources 其實指向同一塊記憶體,是同一個物件。而在橫豎屏切換、且應用為兩種狀態提供了不同資源的情況下,橫屏與豎屏下的 ContextImpl 存取的就不是同一個資源物件了。

Resources 物件的建立過程

讀 Resources 的原始碼可以知道,它對資源的存取實際上是透過 AssetManager 完成。那麼如何建立一個 Resources 物件?有人會問:直接 getResources 不就夠了,幹嘛自己建?答案是:某些特殊場景你確實需要自己建,最典型的就是動態載入 apk。

先看它的公開建構子:

/**
 * Create a new Resources object on top of an existing set of assets in an AssetManager.
 *
 * @param assets Previously created AssetManager.
 * @param metrics Current display metrics to consider when selecting/computing resource values.
 * @param config Desired device configuration to consider when selecting/computing resource values.
 */
public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
    this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null);
}

public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
        CompatibilityInfo compatInfo, IBinder token) {
    mAssets = assets;
    mMetrics.setToDefaults();
    if (compatInfo != null) {
        mCompatibilityInfo = compatInfo;
    }
    mToken = new WeakReference<IBinder>(token);
    updateConfiguration(config, metrics);
    assets.ensureStringBlocks();
}

還有第三個私有的無參數建構子,外部無法存取。從簡便起見採用第一個即可:它接受 AssetManager 與兩個裝置相關的參數,後兩者直接沿用當前應用的設定就行。所以問題的關鍵在於如何建立 AssetManager。

回頭看 ResourcesManager 中的這兩行:

AssetManager assets = new AssetManager();
if (assets.addAssetPath(resDir) == 0) {
    return null;
}

這就是系統建立 AssetManager 的方式。addAssetPath(resDir) 的作用是把該目錄中的資源載入 AssetManager,具體實作在 JNI 層。而 resDir 可以是目錄,也可以是一個 zip 檔。

那麼順著想下去:如果我們把一個未安裝的 apk 路徑傳給這個方法,apk 裡的資源是不是就被載進來了?實測結果確實如此,這正是動態載入 apk 時能取用外掛資源的原理。

/**
 * Add an additional set of assets to the asset manager. This can be
 * either a directory or ZIP file. Not for use by applications. Returns
 * the cookie of the added asset, or 0 on failure.
 * {@hide}
 */
public final int addAssetPath(String path) {
    int res = addAssetPathNative(path);
    return res;
}

注意註解裡的 {@hide}:即使修飾子是 public,Android SDK 匯出時會自動忽略隱藏 API,因此編譯期拿不到,只能透過反射呼叫。

try {
    AssetManager assetManager = AssetManager.class.newInstance();
    Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
    addAssetPath.invoke(assetManager, mDexPath);
    mAssetManager = assetManager;
} catch (Exception e) {
    e.printStackTrace();
}
Resources currentRes = this.getResources();
mResources = new Resources(mAssetManager,
        currentRes.getDisplayMetrics(), currentRes.getConfiguration());

有了自己的 Resources 物件,就能存取其中的各項資源。靠這個技巧可以實作出換膚、切換語言包、動態載入 apk 等特殊功能。

補充:這套寫法在今天需要注意什麼

上述原始碼對應的是 Android 4.x 時代的實作。後續版本中 Resources 與 ResourcesManager 的細節有相當大的變動(例如引入了 ResourcesImpl、AssetManager 改為 createAssetPath() 等 native 方法),反射路徑不一定還成立。更關鍵的是,Google 早已明令禁止反射呼叫非 SDK 介面(灰名單/黑名單機制),高版本上直接反射會被攔截甚至導致崩潰。因此動態載入資源這類需求,現在一律建議走 Bundletool 的 Dynamic Feature Module 或 Play Feature Delivery 這類官方途徑。

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