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






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM