How can I get package name in android?

后端 未结 9 1301
耶瑟儿~
耶瑟儿~ 2020-12-11 05:14

I need to write some util class by myself and I need the packagename of android app. While I found the packageManager which only can be used in Activity and so on that has c

相关标签:
9条回答
  • 2020-12-11 05:26

    Use : getPackageManager().getPackageInfo(getPackageName(), 0).packageName Or just MyContext.getPackageName()

    You can also create a function:

    public String getPackageName(Context context) {
        return context.getPackageName();
    }
    
    0 讨论(0)
  • 2020-12-11 05:30

    The following constant is available without the need for a context.

    BuildConfig.APPLICATION_ID
    
    0 讨论(0)
  • 2020-12-11 05:37

    I think getPackageName() is available directly within activity without calling getApplicationContext. Checked it myself.Working good.

    0 讨论(0)
  • 2020-12-11 05:39

    getApplicationContext().getPackageName() will give the package name.

    0 讨论(0)
  • 2020-12-11 05:39
    List<ApplicationInfo> packages;
        PackageManager pm;
        pm = getPackageManager();
                 get a list of installed apps.
                packages = pm.getInstalledApplications(0);
    
    ActivityManager mActivityManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
    
       for (ApplicationInfo packageInfo : packages) {
       //packageInfo.packageName contains package name
    
    
                          }
    
    0 讨论(0)
  • 2020-12-11 05:39

    you can create a Util Class this way:

    public class AppInfo{
      private static Context cxt;
      public static String PACKAGE_INFO;
      public static String init(Context context){
        cxt = context;
        PACKAGE_INFO = cxt.getPackageName();
      }
    }
    

    then you can use it this way

    public class MyActivity extends Activity{
      @Override
      public void onCreate(Bundle bundle){
        ...
        AppInfo.init(getApplicationContext());
        ...
      }
    }
    

    then you can call it this way:

    public class someClass{
      public void someMethod(){
        String packageInfo = AppInfo.PACKAGE_INFO;
        //Do what you wish
      }
    }
    
    0 讨论(0)
提交回复
热议问题