当前位置:优学网  >  在线题库

如何以静态方法获取任何文件中android的软件包名称

发表时间:2022-07-29 00:41:54 阅读:157

I am trying to get the package name of the app using the below code in my adapter java file. But I am getting nullpointer exception.

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference

Code:

private static boolean appsPackageName() {
        PackageInfo pInfo;
        try {
            pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Could not get package name: " + e);
        }

        if (pInfo.packageName.equals("com.app.sample")) {
            return true;
        } else {
            return  false;
        }
    }
🎖️ 优质答案
  • 您可以在活动中使用此简单代码获取包名称

    getApplicationContext().getPackageName()
    

    如果你没有参加活动,那么你可以使用

    context.getApplicationContext().getPackageName()
    

    在片段中,你可以使用这个

    requireActivity.getApplicationContext().getPackageName()
    
  • 相关问题