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 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)?
Solution 1:
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
.
Solution 2:
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.
Solution 3:
If with the word "anywhere" you mean without having an explicit Context
(for example from a background thread) you should define a class in your project like:
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
Then in your manifest
you need to add this class to the Name
field at the Application
tab. Or edit the xml and put
<application
android:name="com.example.app.MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name"
.......
<activity
......
and then from anywhere you can call
String packagename= MyApp.getContext().getPackageName();
Hope it helps.