5

PackageManager.getApplicationLabel(ApplicationInfo)用来获取应用程序名称。但此名称可能会根据设备区域配置和应用程序资源字符串而改变。

所以我想知道是否有任何方便的方法来获取指定的本地化标签(如果不存在则返回 null )?比如PackageManager.getApplicationLabel(ApplicationInfo info, Locale prefereLocale)

4

1 回答 1

7

首先,让我们描述获取标签的操作顺序:

  1. 获取ApplicationInfo(应用信息有public int labelRes-标签的资源id);
  2. 获取应用程序资源以从中检索labelRes- 使用getResourcesForApplication()
  3. 设置必要的语言环境以获取Resources和检索字符串labelRes(请注意,我没有提到nonLocalizedLabel应该在执行所有上述项目之前检查);

代码本身非常简单(例如来自活动类的代码):

    PackageManager pm = getPackageManager();
    try {
        ApplicationInfo galleryInfo = pm.getApplicationInfo("com.android.gallery3d", PackageManager.GET_META_DATA);

        if (null != galleryInfo) {
            final String label = String.valueOf(pm.getApplicationLabel(galleryInfo));

            Log.w(TAG, "Current app label is " + label);

            final Configuration config = new Configuration();

            config.locale = new Locale("ru");

            final Resources galleryRes = pm.getResourcesForApplication("com.android.gallery3d");

            galleryRes.updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

            final String localizedLabel = galleryRes.getString(galleryInfo.labelRes);

            Log.w(TAG, "Localized app label is " + localizedLabel);
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Failed to obtain app info!");
    }

产生以下输出(第二个字符串标签是我从代码设置的俄语语言环境 - 'ru'):

08-16 19:23:04.425: WARN/MyActivity(29122): Current app label is Gallery
08-16 19:23:04.425: WARN/MyActivity(29122): Localized app label is Галерея
于 2013-08-16T10:28:40.303 回答