引言
本文講解宿主如何從插件apk中獲取到資源,為啥要從插件中獲取資源呢?這種需求可能來(lái)自于顯示插件的名字啊,圖標(biāo)之類的。比如宿主的一個(gè)按鍵上顯示“掃一掃”或者"搖一搖"之類的,這個(gè)字符串是插件提供的。
Demo創(chuàng)建
引入插件的AssetManager
private static AssetManager createAssetManager(String apkPath) {
try {
AssetManager assetManager = AssetManager.class.newInstance();
AssetManager.class.getDeclaredMethod("addAssetPath", String.class).invoke(
assetManager, apkPath);
return assetManager;
} catch (Throwable th) {
th.printStackTrace();
}
return null;
}
獲得插件的Resource
public static Resources getBundleResource(Context context, String apkPath){
AssetManager assetManager = createAssetManager(apkPath);
return new Resources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration());
}
通過(guò)資源名字/類型/插件包名獲取資源
Resources resources = AssertsDexLoader.
getBundleResource(getApplicationContext(),
getApplicationContext().
getDir(AssertsDexLoader.APK_DIR, Context.MODE_PRIVATE).
getAbsolutePath() + "/pluginA.apk");
// 加載字符串
String str = resources.getString(resources.getIdentifier("app_name", "string", "h3c.plugina"));
// 加載圖片
ImageView iv = (ImageView) findViewById(R.id.testIV);
iv.setImageDrawable(resources.getDrawable(resources.getIdentifier("ic_launcher", "mipmap", "h3c.plugina")));
// 加載View
XmlResourceParser layoutParser = mBundleResources.getLayout(mBundleResources.getIdentifier("activity_main", "layout", "h3c.plugina"));
View bundleView = LayoutInflater.from(this).inflate(layoutParser, null);
// findView
TextView tv = (TextView) findViewById(mBundleResources.getIdentifier("pluginATV", "id", "h3c.plugina"));
講解
要想獲得資源文件必須得到一個(gè)Resource對(duì)象,想要獲得插件的資源文件,必須得到一個(gè)插件的Resource對(duì)象,好在android.content.res.AssetManager.java中包含一個(gè)私有方法addAssetPath。只需要將apk的路徑作為參數(shù)傳入,就可以獲得對(duì)應(yīng)的AssetsManager對(duì)象,從而創(chuàng)建一個(gè)Resources對(duì)象,然后就可以從Resource對(duì)象中訪問(wèn)apk中的資源了。
總結(jié)
通過(guò)以上方法卻是可以在宿主中獲取到插件的資源文件,只是宿需要用到相關(guān)資源的時(shí)候需跟插件約定好對(duì)應(yīng)名稱,以防出現(xiàn)找不到的情況。
下一課介紹宿主如何啟動(dòng)插件中的Activity。