Reputation: 393
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)");
Upvotes: 1
Views: 525
Reputation: 9152
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
Upvotes: 2