How to get localized label name from PackageManager

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

So, I wonder if there is any convenient way to get the specified localized shortcut (or return null if it does not exist)? For example, PackageManager.getApplicationLabel(ApplicationInfo info, Locale prefereLocale) ?

+4
source share
1 answer

First of all, let's describe the procedure for getting the label:

  • Get ApplicationInfo (application information public int labelRes - label resource identifier);
  • Get application resources for extracting labelRes from it - using getResourcesForApplication () ;
  • Set the required locale to get Resources and get the string labelRes (note that I did not mention nonLocalizedLabel , which should be checked before all of the above items are executed);

The code itself is quite simple (for example, code from an 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!"); } 

It produces the following output (the second string label is in the Russian locale, which I installed from the 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  
+5
source

Source: https://habr.com/ru/post/1497370/


All Articles