adplus-dvertising

How to get package name from anywhere?

Asked 11 years ago
Viewed 394.08 k times

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

asked 11 years ago

Correct Answer

An idea is to have a static variable in your main activity, instantiated to be the package name. Then just reference that variable.

You will have to initialize it in the main activity's onCreate() method:

Global to the class:

public static String PACKAGE_NAME;

Then..

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PACKAGE_NAME = getApplicationContext().getPackageName();
}

You can then access it via Main.PACKAGE_NAME.

answered 7 years ago

Other Answer

If you use the gradle-android-plugin to build your app, then you can use

BuildConfig.APPLICATION_ID

to retrieve the package name from any scope, incl. a static one.

answered 11 years ago