从PackageManager获取本地化标签名称的方法

时间:2013-08-16 05:09:05

标签: android android-package-managers

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

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

1 个答案:

答案 0 :(得分:6)

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

  1. 获取ApplicationInfo(申请信息有public int labelRes - 标签的资源ID);
  2. 使用getResourcesForApplication();
  3. 获取应用程序资源以从中检索labelRes
  4. 设置必要的区域设置以获取Resources并检索字符串labelRes(请注意,在执行上述所有项目之前,我没有提及nonLocalizedLabel应该检查);
  5. 代码本身非常简单(例如来自活动类的代码):

        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 Галерея