android, how to get package name?

后端 未结 6 2153
长发绾君心
长发绾君心 2021-02-20 02:50

In my application I need to know the name of package name. I have no problem when I want to grab it in activities but i can\'t take it in other classes. Following code is workin

相关标签:
6条回答
  • 2021-02-20 03:00

    Use following

    ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
    
                            String packageName2 = am.getRunningTasks(1).get(0).topActivity.getPackageName();
    
    0 讨论(0)
  • 2021-02-20 03:06

    The simple, or another way is to pass Context into the helper class constructor:

    MyClassConstructor(Context context){
    
            String packageName = context.getPackageName(); 
    }
    
    0 讨论(0)
  • 2021-02-20 03:06

    If you use gradle build, use this: BuildConfig.APPLICATION_ID to get the package name of the application.

    0 讨论(0)
  • getApplicationContext() is a method of ContextWrapper ( super class of Activity).

    If you want to use it in your classes you will have to pass a reference of a Context or its subclass and then use it

    http://developer.android.com/reference/android/content/ContextWrapper.html#getPackageName()

    class MyClass {
        Context mContext;
    
        public MyClass(Context ctx) [
            this.mContext = ctx;
    
        }
    
        String getPackageName() {
            mContext.getPackageName();
        }
    
    }
    
    0 讨论(0)
  • 2021-02-20 03:14

    Simplest answer is make a class name constructor and pass the ApplicationContext in that constructor -

    ClassConstructor(Context context){
    
            String packageName = context.getPackageName(); 
    }
    
    0 讨论(0)
  • 2021-02-20 03:16

    Using instance of the class you can get package name by using getClass().getPackage().getName() to the instance

    Sample Code

    ClassA instanceOfClass = new ClassA();
    String packageName = instanceOfClass.getClass().getPackage().getName();
    System.out.println("Package Name = " + packageName);
    
    0 讨论(0)
提交回复
热议问题