Android之基于AssetManager实现换肤方案
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