Hesam
Hesam

Reputation: 53610

android, how to get package name?

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 working in activity but i don't know why it has problem in simple class.

String packageName = getPackageName();

In my class I tried to write this code:

Context context = getApplicationContext();
String packageName = context.getPackageName();

but compiler said getApplicationContext() method is undefined for this class.

How can I take package name within this class?

Upvotes: 17

Views: 40297

Answers (8)

Sanved
Sanved

Reputation: 941

In case someone is looking for this in Kotlin -

var pName = this.packageName

Upvotes: 2

Martin4code
Martin4code

Reputation: 99

MAUI:

// In class MainActivity : MauiAppCompatActivity
string? packageName = ApplicationContext.ApplicationInfo.PackageName;

Upvotes: -1

Anurag Mishra
Anurag Mishra

Reputation: 103

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

ClassConstructor(Context context){

        String packageName = context.getPackageName(); 
}

Upvotes: 0

Mahendra Liya
Mahendra Liya

Reputation: 13218

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

Upvotes: 3

Lumis
Lumis

Reputation: 21629

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

MyClassConstructor(Context context){

        String packageName = context.getPackageName(); 
}

Upvotes: 20

Rajdeep Dua
Rajdeep Dua

Reputation: 11230

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();
    }

}

Upvotes: 0

bindal
bindal

Reputation: 1932

Use following

ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);

                        String packageName2 = am.getRunningTasks(1).get(0).topActivity.getPackageName();

Upvotes: 0

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53687

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

Upvotes: 16

Related Questions