如何从另一个应用程序访问字符串资源

3

我有两个应用程序'A'和'B'。

假设,我在应用程序'A'中有一个字符串资源

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

我如何从'B'中的Activity访问abc的值。

我尝试了以下方法。

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){

}

始终返回0,无论什么情况下都是resId。请问我是否可以从应用程序“B”访问字符串abc?

谢谢, SANAT

2个回答

9
可以实现!看看下面的代码,对我有效。
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();
    }

}

希望这会对你有所帮助。

1
似乎没问题。这是我的代码。
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));
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接