从包名称中获取应用程序名称

时间:2013-12-03 15:25:46

标签: java android xml

我正在尝试插入应用程序的名称作为首选项摘要。我编写了这段代码,但它不起作用,因为当我运行应用程序时,在此行中出现NullPointerException

name.setSummary(Pm.getApplicationLabel(nameApp));

代码是

    value2 = getIntent().getStringExtra("ApplicationName");

    PackageManager Pm = getPackageManager();

    ApplicationInfo nameApp = Pm.getApplicationInfo(value2, 0);

    name.setSummary(Pm.getApplicationLabel(nameApp));

Value2是一个变量的名称,该变量取自前一个Activity的包的名称,并且此步骤运行良好,因为包的名称已正确传递和恢复

2 个答案:

答案 0 :(得分:2)

试试这个..

    PackageManager packageManager=this.getPackageManager();
    List<ApplicationInfo applist=packageManager.getInstalledApplications(0);


    Iterator<ApplicationInfo> it=applist.iterator();
    while(it.hasNext()){
        ApplicationInfo pk=(ApplicationInfo)it.next();

        String appname = packageManager.getApplicationLabel(pk).toString();
        System.out.println("Application name : "+appname);
    }

或特定包名称

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)");
System.out.println("Application name : "+applicationName);

答案 1 :(得分:0)

尝试使用此方法,用于包

Resources appR = ctx.getResources();
CharSequence txt = appR.getText(appR.getIdentifier("app_name",
"string", ctx.getPackageName()));

并且应用程序名称使用PackageManager#getApplicationInfo()