Вопрос

I am using PackageManager.getApplicationLabel(ApplicationInfo) to get the application name. But this name may change according to the device locale configuration and application resource string.

So I wonder if there is any convenient way to get a specified localized label (or return null if not exist)? Such as PackageManager.getApplicationLabel(ApplicationInfo info, Locale prefereLocale)?

Это было полезно?

Решение

First of all, lets describe order of actions to obtain the label:

  1. Obtain ApplicationInfo (application info has public int labelRes - resource id of the label);
  2. Obtain application resources to retrieve labelRes from it - using getResourcesForApplication();
  3. Set necessary locale to obtained Resources and retrieve string labelRes (please note, that I haven't mentioned nonLocalizedLabel which should be checked before doing all above items);

The code itself is pretty simple (e.g. code from activity class):

    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!");
    }

Produces the following output (second string label is in Russian locale which I set from code - '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 Галерея
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top