The third part of Android plug-in development [load plug-in resources]

introduction


This article explains how the host obtains resources from the plug-in apk, why should it obtain resources from the plug-in? This requirement may come from displaying the name of the plug-in, icon and so on. For example, "Scan" or "Shake" is displayed on a button of the host. This string is provided by the plug-in.

Demo creation


AssetManager that introduces plugins

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;
}

Get the Resource of the plugin

public static Resources getBundleResource(Context context, String apkPath){
    AssetManager assetManager = createAssetManager(apkPath);
    return new Resources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration());
}

Get resources by resource name/type/plugin package name

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 can refer to here ]

explain


If you want to get a resource file, you must get a Resource object. If you want to get a plug-in resource file, you must get a plug-in Resource object. Fortunately, android.content.res.AssetManager.java contains a private method addAssetPath . You only need to pass in the path of the apk as a parameter to obtain the corresponding AssetsManager object, thereby creating a Resources object, and then you can access the resources in the apk from the Resource object.

Summarize


Through the above methods, the resource files of the plug-in can be obtained in the host, but when the host needs to use the relevant resources, it is necessary to agree on the corresponding name with the plug-in, in case it cannot be found.

The next lesson describes how the host loads the plugin layout.

Guess you like

Origin blog.csdn.net/h3c4lenovo/article/details/50731943