Getting resources of another Application

妖精的绣舞 提交于 2019-11-27 13:45:47

If you are the developer of both applications then the right approach would be, as othes noted, to create an Android library project and share it between apps.

Nevertheles, you can still access resources from another app, even if this is not your app:

Resources res = context.getPackageManager().getResourcesForApplication("com.example.foo")

If both apps are your own and you want to bundle these resources at build-time:

Create an Android Library Project, put all the needed resources into it and reference it from both your apps.


Edit to your edit: You can use the library in the android market. You just can not use it alone (compile it). You have to build an app that uses the library. When you build that app, all the needed content gets basically grabbed from the library and copied to your apk. Which you can put on the market as usual.

This does not work when you want to access resources from an app that gets downloaded onto the device at runtime. A library project bundles all resources when you build the app that uses it. Peter Knego's response is the correct one when accessing at runtime.

It is possible if those both application are yours. Or you can used any Android Library for both these application. If you want you also create your own Android Library for this kind of work. Thnx.

Chris Sprague

Peter's answer above is great, but I'd like to elaborate a little more...

When you control appA and appB and want to get a drawable from appB, while in appA, then do the following:

  1. Get the identifier of the drawable when in appB (for example, R.drawable.iconInAppB)
  2. Then, in appA

    Resources res = context.getPackageManager().getResourcesForApplication("com.example.appB");
    
        Drawable d = res.getDrawable(integer);
    //integer was what appB assigned to R.drawable.iconInAppB
    

*Note: The integer id assigned to R.drawable.iconInAppB will change over time so don't rely on hardcoding. I save the key-value pairs (String resourceName, int resourceId) in a database in appB and access them using a content provider.

For example, let's get the string-array with the ID of entryvalues_font_size from the package com.android.settings

String[] enries = null;
try {
    // You can get PackageManager from the Context
    Resources res = getPackageManager().getResourcesForApplication("com.android.settings");
    int resId = res.getIdentifier("entryvalues_font_size", "array", "com.android.settings");
    if (resId != 0) {
        enries = res.getStringArray(resId);
    }
}
catch (NameNotFoundException e) {
    e.printStackTrace();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!