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

mia*_*shu 4 android android-package-managers

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

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

san*_*tar 6

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

  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!");
    }
Run Code Online (Sandbox Code Playgroud)

生成以下输出(第二个字符串标签是俄语语言环境,我从代码中设置 - '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 ???????
Run Code Online (Sandbox Code Playgroud)