在Android 插件化技术中(宿主app和插件app设置相同的sharedUserId),动态加载apk有两种方式:app
下面介绍几种常见的方法获取资源以及代码的方法。函数
try { context = createPackageContext("com.test.resource", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); textView.setText(context.getResources().getText(R.string.message)); } catch (NameNotFoundException e) { e.printStackTrace(); }
新建一个获取资源的接口,传入插件APK的路径返回Resources对象布局
// 获取插件apk的Resources对象 public Resources getBundleResource(Context context, String apkPath) { AssetManager assetManager = createAssetManager(apkPath); return new Resources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration()); } private 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 对象以后,就能够经过函数resources.getDrawable、resources.getString、resources.getLayout 获取图片、字符串、布局文件了。spa