ef2011 ef2011 - 2 years ago 149
Android Question

How to get package name from anywhere?

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

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

Answer Source

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;


public void onCreate(Bundle savedInstanceState) {

    PACKAGE_NAME = getApplicationContext().getPackageName();

You can then access it via Main.PACKAGE_NAME.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download