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)?
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
.
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.
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.
链接地址: http://www.djcxy.com/p/71150.html上一篇: 在包中描述字段
下一篇: 如何从任何地方获取包名?