Android插件化开发 第三篇 [加载插件资源]

引言


本文讲解宿主如何从插件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")));

[Demo可参考这里]

讲解


要想获得资源文件必须得到一个Resource对象,想要获得插件的资源文件,必须得到一个插件的Resource对象,好在android.content.res.AssetManager.java中包含一个私有方法addAssetPath。只需要将apk的路径作为参数传入,就可以获得对应的AssetsManager对象,从而创建一个Resources对象,然后就可以从Resource对象中访问apk中的资源了。

总结


通过以上方法却是可以在宿主中获取到插件的资源文件,只是宿需要用到相关资源的时候需跟插件约定好对应名称,以防出现找不到的情况。

下一课介绍宿主如何加载插件layout。

猜你喜欢

转载自blog.csdn.net/h3c4lenovo/article/details/50731943
今日推荐