Sanat
Sanat

Reputation: 71

How to access String resource from another application

I have a application 'A' and application 'B'.

Say, I have a string resource in the application 'A'

<\string name="abc">ABCDEF<\/string>

How do I access the value of abc from the Activity in 'B'.

I tried the following method.

try {
    PackageManager pm = getPackageManager();

    ComponentName component = new ComponentName(
        "com.android.myhome",
        "com.android.myhome.WebPortalActivity");
    ActivityInfo activityInfo = pm.getActivityInfo(component, 0);
    Resources res = pm.getResourcesForApplication(activityInfo.applicationInfo);
    int resId = res.getIdentifier("abc", "string", null);
}
catch(NameNotFoundException e){

}

Always resId is returned 0 always.. Can anyone please let me know if I could access string abc from the application 'B'

Regards, SANAT

Upvotes: 3

Views: 6160

Answers (2)

androidyue
androidyue

Reputation: 1112

It is possible! Take a look at the following code. It works for me.

public void testUseAndroidString() {
    Context context = getContext();
    Resources res = null;
    try {
        //I want to use the clear_activities string in Package com.android.settings
        res = context.getPackageManager().getResourcesForApplication("com.android.settings");
        int resourceId = res.getIdentifier("com.android.settings:string/clear_activities", null, null);
        if(0 != resourceId) {
            CharSequence s = context.getPackageManager().getText("com.android.settings", resourceId, null);
            Log.i(VIEW_LOG_TAG, "resource=" + s);
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

}

Hope this will help you.

Upvotes: 9

landry
landry

Reputation: 561

It seems Ok. Here is my code

Resources res = null;
    try {
        res = getPackageManager().getResourcesForApplication("com.sjm.testres1");
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if(null != res) {
        int sId = res.getIdentifier("com.sjm.testres1:string/app_name1", null, null);
        int dId = res.getIdentifier("com.sjm.testres1:drawable/card_1_big", null, null);
        if(0 != dId) {
            iv.setBackgroundDrawable(res.getDrawable(dId));
        }
        if(0 != sId) {
            tv.setText(res.getString(sId));
        }
    }

Upvotes: 1

Related Questions