How to get package name from anywhere?

Viewed 424560

I am aware of the availability of Context.getApplicationContext() and View.getContext(), through which I can actually call Context.getPackageName() to retrieve the package name of an application.

They work if I call from a method to which a View or an Activity object is available, but if I want to find the package name from a totally independent class with no View or Activity, is there a way to do that (directly or indirectly)?

15 Answers

For those who are using Gradle, as @Billda mentioned, you can get the package name via:

BuildConfig.APPLICATION_ID

This gives you the package name declared in your app gradle:

android {
    defaultConfig {
        applicationId "com.domain.www"
    }
}

If you are interested to get the package name used by your java classes (which sometimes is different than applicationId), you can use

BuildConfig.class.getPackage().toString()

If you are confused which one to use, read here:

Note: The application ID used to be directly tied to your code's package name; so some Android APIs use the term "package name" in their method names and parameter names, but this is actually your application ID. For example, the Context.getPackageName() method returns your application ID. There's no need to ever share your code's true package name outside your app code.

Just use this code

val packageName = context.packageName 

Use: BuildConfig.APPLICATION_ID to get PACKAGE NAME anywhere( ie; services, receiver, activity, fragment, etc )

Example: String PackageName = BuildConfig.APPLICATION_ID;

Just import Android.app,then you can use: <br/>Application.getProcessName()<br/>

Get the current Application Process Name without context, view, or activity.

BuildConfig.APPLICATION_ID and package may not always be the same. Use "buildConfigField" to have gradle add package to the BuildConfig and access as BuildConfig.PACKAGE. https://developer.android.com/studio/build/gradle-tips

defaultConfig {
    applicationId "com.example.app.name"
    minSdkVersion 24
    targetSdkVersion 29
    versionCode 1
    versionName '0.1.0'
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    buildConfigField("String", "PACKAGE", "\"com.example.app\"")
}

This works for me in kotlin

       override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       
        var packageName=applicationContext.packageName // need to put this line
        Log.d("YourTag",packageName)
}
Related