Android - How to get application name? (Not package name)

后端 未结 12 2170
天涯浪人
天涯浪人 2020-11-27 15:17

In my manifest I have:

  

        
相关标签:
12条回答
  • 2020-11-27 15:27

    If you need only the application name, not the package name, then just write this code.

     String app_name = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
    
    0 讨论(0)
  • 2020-11-27 15:27

    Get Appliction Name Using RunningAppProcessInfo as:

    ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
    List l = am.getRunningAppProcesses();
    Iterator i = l.iterator();
    PackageManager pm = this.getPackageManager();
    while(i.hasNext()) {
      ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
      try {
        CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
        Log.w("LABEL", c.toString());
      }catch(Exception e) {
        //Name Not FOund Exception
      }
    }
    
    0 讨论(0)
  • 2020-11-27 15:28

    If you know Package name then Use following snippet

    ApplicationInfo ai;
    try {
        ai = pm.getApplicationInfo(packageName, 0);
    } catch (final NameNotFoundException e) {
        ai = null;
    }
    final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
    
    0 讨论(0)
  • 2020-11-27 15:28

    The source comment added to NonLocalizedLabel directs us now to:

    return context.getPackageManager().getApplicationLabelFormatted(context.getApplicationInfo());
    
    0 讨论(0)
  • 2020-11-27 15:32

    From any Context use:

    getApplicationInfo().loadLabel(getPackageManager()).toString();
    
    0 讨论(0)
  • 2020-11-27 15:34

    There's an easier way than the other answers that doesn't require you to name the resource explicitly or worry about exceptions with package names. It also works if you have used a string directly instead of a resource.

    Just do:

    public static String getApplicationName(Context context) {
        ApplicationInfo applicationInfo = context.getApplicationInfo();
        int stringId = applicationInfo.labelRes;
        return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
    }
    

    Hope this helps.

    Edit

    In light of the comment from Snicolas, I've modified the above so that it doesn't try to resolve the id if it is 0. Instead it uses, nonLocalizedLabel as a backoff. No need for wrapping in try/catch.

    0 讨论(0)
提交回复
热议问题