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

Android插件化實戰:動態加載未安裝apk的Resource資源

編輯:關於 Android 開發

Android插件化實戰:動態加載未安裝apk的Resource資源

在插件化開發中,如何加載一個尚未安裝的apk裡的資源檔,是必須攻克的難題。本文將從源碼層面出發,一步步帶你實現這個能力。

核心思路:從AssetManager下手

翻閱 android.content.res.AssetManager.java 的源碼會發現,其中藏著一個私有方法 addAssetPath。只要把apk的路徑作為參數傳入,就能取得對應的AssetManager物件,進而據此建立Resources物件,最終便能存取apk內的資源。整個流程可濃縮為三步:

1. 建立一個AssetManager物件;
2. 透過反射呼叫addAssetPath方法;
3. 以AssetManager為參數建立Resources物件。

程式碼實作

package net.mobctrl.hostapk;

import java.io.File;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;

/**
 * @Author Zheng Haibo
 * @version $Id: LoaderResManager.java, v 0.1 2015年12月11日 下午7:58:59 mochuan.zhb
 * @Description 動態加載資源的管理器
 */
public class BundlerResourceLoader {

    private static AssetManager createAssetManager(String apkPath) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            try {
                AssetManager.class.getDeclaredMethod("addAssetPath", String.class)
                        .invoke(assetManager, apkPath);
            } catch (Throwable th) {
                System.out.println("debug:createAssetManager :" + th.getMessage());
                th.printStackTrace();
            }
            return assetManager;
        } catch (Throwable th) {
            System.out.println("debug:createAssetManager :" + th.getMessage());
            th.printStackTrace();
        }
        return null;
    }

    /**
     * 獲取Bundle中的資源
     */
    public static Resources getBundleResource(Context context) {
        AssetsManager.copyAllAssetsApk(context);
        File dir = context.getDir(AssetsManager.APK_DIR, Context.MODE_PRIVATE);
        String apkPath = dir.getAbsolutePath() + "/BundleApk.apk";
        System.out.println("debug:apkPath = " + apkPath + ",exists=" + (new File(apkPath).exists()));
        AssetManager assetManager = createAssetManager(apkPath);
        return new Resources(assetManager,
                context.getResources().getDisplayMetrics(),
                context.getResources().getConfiguration());
    }
}

DEMO演示

特別提醒:使用Resources物件取得資源時,傳入的ID必須是離線apk中R檔案對應的資源ID。若使用getIdentifier方法,三個參數分別為資源名稱、資源類型,以及離線apk的套件名稱——千萬別忘了第三個參數。

Resources resources = BundlerResourceLoader.getBundleResource(getApplicationContext());
imageView = (ImageView) findViewById(R.id.image_view_iv);
if (resources != null) {
    String str = resources.getString(resources.getIdentifier("test_str", "string", "net.mobctrl.normal.apk"));
    String strById = resources.getString(0x7f050001); // id參照Bundle apk中的R檔案
    System.out.println("debug:" + str);
    Toast.makeText(getApplicationContext(), strById, Toast.LENGTH_SHORT).show();
    Drawable drawable = resources.getDrawable(0x7f020000); // id參照Bundle apk中的R檔案
    imageView.setImageDrawable(drawable);
}

以上程式碼示範了加載離線apk中的字串與Drawable資源,那麼layout資源該如何處理呢?

問題引入

我們一般使用LayoutInflater來載入佈局:

View view = LayoutInflater.from(context).inflate(R.layout.main_fragment, null);

其中 R.layout.main_fragment 的ID可以透過上述方法取得,關鍵在於如何取得一個合適的context——直接傳入當前的context顯然行不通。解決方案有兩種:

- 1. 自訂一個ContextImpl並覆寫其方法;
- 2. 透過反射直接替換當前context的mResources私有成員變數。

這裡我們採用第二種方案:

@Override
protected void attachBaseContext(Context context) {
    replaceContextResources(context);
    super.attachBaseContext(context);
}

/**
 * 使用反射的方式,用Bundle的Resource物件替換Context的mResources物件
 */
public void replaceContextResources(Context context) {
    try {
        Field field = context.getClass().getDeclaredField("mResources");
        field.setAccessible(true);
        field.set(context, mBundleResources);
        System.out.println("debug:repalceResources succ");
    } catch (Exception e) {
        System.out.println("debug:repalceResources error");
        e.printStackTrace();
    }
}

我們在Activity的attachBaseContext方法中替換掉Context的mResources,如此一來,便能成功載入離線apk裡的佈局檔了。

透視資源檔的打包過程

要真正做到插件化,就必須理解Android資源檔的打包機制,如此才能為每個插件編號,並依規則生成R檔案。以攜程DynamicAPK為例,它對插件R檔案的編碼規則如下:

1. R檔案為int型,前8位代表插件Id(Host固定為0x7f,Android系統自帶的則以0x01開頭);
2. 緊接的8位用於區分資源類型,如layout、id、string、dimen等;
3. 最後16位為資源的流水編號。

依照這套規則生成對應的插件apk後,於執行階段我們可以撰寫一個ResourceManager類別(繼承自Resources),並將所有Activity的mResources成員替換為該類別,再覆寫其方法。載入資源時,只需根據id的前綴判斷所屬插件,轉而查找對應插件的Resource即可——本質上就是用一個統一的分發器來調度。

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