获取知道包名称的应用名称

时间:2013-12-05 17:41:07

标签: java android xml

我想知道应用程序的名称是否可以访问包名。我能怎么做?我写了这段代码,但我不确定我做了什么。

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

1 个答案:

答案 0 :(得分:2)

试试这个:

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

你所做的也是正确的。只有你可能想把它放在try catch中以防止异常导致应用程序崩溃