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

Android 動態資源載入原理與換膚實作剖析

編輯:關於 Android 程式設計

換膚、主題切換、插件化資源的底層原理,其實都指向同一件事:能不能讓 App 在執行期讀到「另一個 APK」裡的資源。要回答這個問題,得先弄清楚系統原生的 Resources 是怎麼被建立起來的。

一、getResources() 背後發生了什麼

我們最熟悉的一句話是:

public Resources getResources() {
    return mResources;
}

而 mResources 是在 ContextImpl 初始化時建立的:

mResources = mPackageInfo.getResources(mainThread);

跟進 LoadedApk:

public Resources getResources(ActivityThread mainThread) {
    if (mResources == null) {
        mResources = mainThread.getTopLevelResources(
                mResDir, Display.DEFAULT_DISPLAY, null, this);
    }
    return mResources;
}

再走進 ActivityThread 的 getTopLevelResources()(省略部分日誌與註解):

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

    // 快取沒有,重新建立
    AssetManager assets = new AssetManager();
    assets.setThemeSupport(compInfo.isThemeable);
    if (assets.addAssetPath(resDir) == 0) {
        return null;
    }
    r = new Resources(assets, dm, config, compInfo);

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

這段邏輯的重點有兩個。第一,ResourcesKey 主要由 resDir 決定,也就是 APK 檔案所在的路徑。第二,系統用一個 Map(mActiveResources)維護「ResourcesKey → 弱引用 Resources」的對應關係,命中就直接复用,沒命中才建立。

結論很關鍵:既然 Resources 的實例是以資源路徑為索引來快取的,那麼只要我們能給它一個不同的路徑,就能讀到另一份資源。

二、AssetManager 裡到底裝了哪些東西

建立 Resources 的關鍵三行:

AssetManager assets = new AssetManager();
assets.setThemeSupport(compInfo.isThemeable);
if (assets.addAssetPath(resDir) == 0) {
    return null;
}
r = new Resources(assets, dm, config, compInfo);

AssetManager 的建構子會呼叫 native 的 init():

public AssetManager() {
    synchronized (this) {
        if (DEBUG_REFS) {
            mNumRefs = 0;
            incRefsLocked(this.hashCode());
        }
        init();
        ensureSystemAssets();
    }
}

其 native 實作在 android_util_AssetManager.cpp:

static void android_content_AssetManager_init(JNIEnv* env, jobject clazz) {
    AssetManager* am = new AssetManager();
    if (am == NULL) {
        jniThrowException(env, "java/lang/OutOfMemoryError", "");
        return;
    }
    // 把 Framework 的資源加入 AssetManager 的搜尋路徑
    am->addDefaultAssets();
    env->SetIntField(clazz, gAssetManagerOffsets.mObject, (jint)am);
}

bool AssetManager::addDefaultAssets() {
    // /system
    const char* root = getenv("ANDROID_ROOT");
    LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
    String8 path(root);
    // kSystemAssets = "framework/framework-res.apk"
    static const char* kSystemAssets = "framework/framework-res.apk";
    path.appendPath(kSystemAssets);
    return addAssetPath(path, NULL);
}

也就是說,AssetManager 一誕生就已經包含了 /system/framework/framework-res.apk,接著再加上本應用的資源路徑。這正好解釋了為什麼我們用 getResources() 拿到的物件,既能讀系統資源、也能讀自己的資源。

而 addAssetPath 同樣是 native 方法:

/** 加入額外的資源集,可以是目錄或 ZIP 檔。Not for use by applications. */
public native final int addAssetPath(String path);
static jint android_content_AssetManager_addAssetPath(
        JNIEnv* env, jobject clazz, jstring path) {
    ScopedUtfChars path8(env, path);
    if (path8.c_str() == NULL) {
        return 0;
    }
    AssetManager* am = assetManagerForJavaObject(env, clazz);
    if (am == NULL) {
        return 0;
    }
    void* cookie;
    // 在 native 層完成資源路徑的加入
    bool res = am->addAssetPath(String8(path8.c_str()), &cookie);
    return (res) ? (jint)cookie : 0;
}

三、自己動手做一份 Resources

思路至此已經很清楚:自建一個 AssetManager,用 addAssetPath 塞入目標 APK 的路徑,再用它建構一個新的 Resources,之後所有資源讀取都走這個物件。唯一的障礙是 addAssetPath 被標記為 hide,用反射即可繞過。

public void loadRes(String path) {
    try {
        assetManager = AssetManager.class.newInstance();
        Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
        addAssetPath.invoke(assetManager, path);
    } catch (Exception e) {
        e.printStackTrace();
    }
    resources = new Resources(assetManager,
            super.getResources().getDisplayMetrics(),
            super.getResources().getConfiguration());
}

其中 path 是目標 APK 的實際路徑,可以這樣取得:

getPackageManager().getApplicationInfo("xxx", 0).sourceDir;

接著覆寫 Context 的兩個方法,讓整份程式碼保持一致,呼叫端完全不需要改寫:

@Override
public Resources getResources() {
    return resources == null ? super.getResources() : resources;
}

@Override
public AssetManager getAssets() {
    return assetManager == null ? super.getAssets() : assetManager;
}

四、換膚效果實作

場景是這樣的:預設風格使用 App 自帶的資源;另一種風格則放在一個只包含資源的獨立插件 APK 中,切換時動態載入對應資源。

風格一風格二

宿主程式碼:

private AssetManager assetManager;
private Resources resources;
private RadioGroup rg;
private ImageView iv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    iv = (ImageView) findViewById(R.id.iv);
    rg = (RadioGroup) findViewById(R.id.rg);

    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.default_skin:
                    assetManager = null;
                    resources = null;
                    iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
                    break;
                case R.id.skin1:
                    String dexPath = "";
                    try {
                        dexPath = getPackageManager()
                                .getApplicationInfo("com.example.plugin", 0).sourceDir;
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    loadRes(dexPath);
                    // 由於已覆寫 getResources(),這裡取到的是插件資源
                    iv.setImageDrawable(getResources().getDrawable(0x7f020000));
                    break;
            }
        }
    });
}

這裡用 0x7f020000 硬編碼了資源 ID,僅是為了說明原理。實務上耦合這麼高很難維護,比較好的做法是讓插件提供一個取得 ID 的方法:

public class Plugin {
    public static int getImageId() {
        return R.drawable.ic_launcher;
    }
}

宿主再用 DexClassLoader 反射呼叫:

private void setImage(String dexPath) {
    DexClassLoader loader = new DexClassLoader(dexPath,
            getApplicationInfo().dataDir, null,
            this.getClass().getClassLoader());
    try {
        Class<?> clazz = loader.loadClass("com.example.plugin.Plugin");
        Method getImageId = clazz.getMethod("getImageId");
        int imageId = (int) getImageId.invoke(clazz);
        iv.setImageDrawable(getResources().getDrawable(imageId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

五、插件發現與管理

怎麼知道手機裡有哪些插件可用?一個常見做法是讓每個插件在 AndroidManifest.xml 中宣告一個空的 Activity,並掛上自訂的 action:

<activity android:name=".plugin">
    <intent-filter>
        <action android:name="android.intent.plugin" />
    </intent-filter>
</activity>

宿主透過 PackageManager 就能把它們全部撈出來:

PackageManager pm = getPackageManager();
List<ResolveInfo> resolveinfos = pm.queryIntentActivities(intent, 0);
ActivityInfo activityInfo = resolveinfos.get(i).activityInfo;
dexPaths.add(activityInfo.applicationInfo.sourceDir);

插件風格切換插件風格切換插件風格切換

完整的宿主實作:

private AssetManager assetManager;
private Resources resources;
private LinearLayout ll;
private ImageView iv;
private Button btn;
private final List<String> dexPaths = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    iv = (ImageView) findViewById(R.id.iv);
    ll = (LinearLayout) findViewById(R.id.ll);
    btn = (Button) findViewById(R.id.btn);

    // 還原預設風格
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resources = null;
            iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
        }
    });

    Intent intent = new Intent("android.intent.plugin");
    PackageManager pm = getPackageManager();
    final List<ResolveInfo> resolveinfos = pm.queryIntentActivities(intent, 0);

    for (int i = 0; i < resolveinfos.size(); i++) {
        final ActivityInfo activityInfo = resolveinfos.get(i).activityInfo;
        dexPaths.add(activityInfo.applicationInfo.sourceDir);

        // 依插件數量動態產生按鈕
        final Button skinBtn = new Button(this);
        skinBtn.setText("風格" + (i + 1));
        skinBtn.setTag(i);
        ll.addView(skinBtn, new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        skinBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = (Integer) v.getTag();
                loadRes(dexPaths.get(index));
                setImage(resolveinfos.get(index).activityInfo);
            }
        });
    }
}

private void setImage(ActivityInfo activityInfo) {
    DexClassLoader loader = new DexClassLoader(
            activityInfo.applicationInfo.sourceDir,
            getApplicationInfo().dataDir, null,
            this.getClass().getClassLoader());
    try {
        Class<?> clazz = loader.loadClass(activityInfo.packageName + ".Plugin");
        Method getImageId = clazz.getMethod("getImageId");
        int imageId = (int) getImageId.invoke(clazz);
        iv.setImageDrawable(getResources().getDrawable(imageId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void loadRes(String path) {
    try {
        assetManager = AssetManager.class.newInstance();
        Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
        addAssetPath.invoke(assetManager, path);
    } catch (Exception e) {
        e.printStackTrace();
    }
    resources = new Resources(assetManager,
            super.getResources().getDisplayMetrics(),
            super.getResources().getConfiguration());
}

@Override
public Resources getResources() {
    return resources == null ? super.getResources() : resources;
}

@Override
public AssetManager getAssets() {
    return assetManager == null ? super.getAssets() : assetManager;
}

插件端結構非常簡單,com.example.plugin 與 com.example.plugin2 各自只有一個 Plugin.java(內容一致,供宿主反射呼叫),加上一份上面提過的空 Activity 宣告。

六、這種做法的限制

把原理講通之外,也該說清楚代價。資源 ID 在不同 APK 中並不保證一致,硬編碼 ID 或依賴對方回傳 ID 都很脆弱;此外 addAssetPath 是隱藏 API,跨版本升級時有失效風險;自建 Resources 也繞開了系統的資源快取管理。因此這套思路適合用來理解 Android 資源體系,或作為輕量換膚方案的參考;若要做完整的插件化,通常還需要一層資源 ID 重映射與相容性處理。

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