Android外掛化開發 第三篇 [載入外掛資源]
阿新 • • 發佈:2019-01-23
引言
本文講解宿主如何從外掛apk中獲取到資源,為啥要從外掛中獲取資源呢?這種需求可能來自於顯示外掛的名字啊,圖示之類的。比如宿主的一個按鍵上顯示“掃一掃”或者"搖一搖"之類的,這個字串是外掛提供的。
Demo建立
引入外掛的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());
}
通過資源名字/型別/外掛包名獲取資源
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"));
講解
要想獲得資原始檔必須得到一個Resource物件,想要獲得外掛的資原始檔,必須得到一個外掛的Resource物件,好在android.content.res.AssetManager.java中包含一個私有方法addAssetPath。只需要將apk的路徑作為引數傳入,就可以獲得對應的AssetsManager物件,從而建立一個Resources物件,然後就可以從Resource物件中訪問apk中的資源了。
總結
通過以上方法卻是可以在宿主中獲取到外掛的資原始檔,只是宿需要用到相關資源的時候需跟外掛約定好對應名稱,以防出現找不到的情況。
下一課介紹宿主如何啟動外掛中的Activity。
文/H3c(簡書作者)
原文連結:http://www.jianshu.com/p/30d65b7b6890
著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。