AssetManager的addAssetPath負責將另外一個apk的資源文件加載進當前應用,這裏因爲是api隱藏方法,採用反射方式調用。
查看
addAssetPath方法註釋,容許傳遞的路徑爲資源目錄或者zip文件。
/**
* 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}
*/
經過實例化的AssetManager對象,生成插件包對應的Resources對象,拿到該對象便可操做插件包的相關資源文件。
private Resources pluginRes;//插件Resource對象
private String pluginApkPackageName;//插件Apk的包名
public ResPluginOnAssetManagerPattern initManager(Context curContext, String pluginApkPath) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, PackageManager.NameNotFoundException, ClassNotFoundException {
AssetManager assetManager = AssetManager.class.newInstance();
Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
addAssetPath.invoke(assetManager, pluginApkPath);
Resources curAppRes = curContext.getResources();
pluginRes = new Resources(assetManager, curAppRes.getDisplayMetrics(), curAppRes.getConfiguration());
pluginApkPackageName = UtilsSystem.getPackageNameThroughApkPath(curContext, pluginApkPath);
return this;
}
想要獲取插件包的資源,能夠經過如下方式引用(這裏僅給出string以及drawable的調用方式,其餘資源相似):
/**
* 獲取ResID
*
* @param resName
* @param resType
* @return
*/
private int getResId(String resName, String resType) {
if (pluginRes != null && !UtilsString.isEmptyBaseTrim(pluginApkPackageName)) {
return pluginRes.getIdentifier(resName, resType, pluginApkPackageName);
}
return -1;
}
@Override
public String getString(String resName) {
return pluginRes.getString(getResId(resName, "string"));
}
@Override
public Drawable getDrawable(String resName) {
return pluginRes.getDrawable(getResId(resName, "drawable"));
}
源碼地址:https://github.com/xiaoxuan948/AndroidUnityLab/tree/master/unity_base_dev_helper/src/main/java/com/coca/unity_base_dev_helper/plugin