简体   繁体   中英

Get app name knowing the name of the package

I would like to know the name of the application will have access to the package name. How can I do? I wrote this code but I'm not sure what I did.

    final PackageManager pm = getApplicationContext().getPackageManager();
    ApplicationInfo ai;
    try {
        ai = pm.getApplicationInfo(packageName, 0);
    } catch (final NameNotFoundException e) {
        ai = null;
    }
    final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");

Try this:

final PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai;
try {
    ai = pm.getApplicationInfo( this.getPackageName(), 0);
} catch (final NameNotFoundException e) {
    ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");

What you did is also correct. Only thing that you might want to put it in a try catch to prevent exception causing the app to crash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM