How to get package name from anywhere?

2019-01-01 08:18发布

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

11条回答
妖精总统
2楼-- · 2019-01-01 08:47

You can use undocumented method android.app.ActivityThread.currentPackageName() :

Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method  = clazz.getDeclaredMethod("currentPackageName", null);
String appPackageName = (String) method.invoke(clazz, null);

Caveat: This must be done on the main thread of the application.

Thanks to this blog post for the idea: http://blog.javia.org/static-the-android-application-package/ .

查看更多
浮光初槿花落
3楼-- · 2019-01-01 08:48

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.

查看更多
只若初见
4楼-- · 2019-01-01 08:54
private String getApplicationName(Context context, String data, int flag) {

   final PackageManager pckManager = context.getPackageManager();
   ApplicationInfo applicationInformation;
   try {
       applicationInformation = pckManager.getApplicationInfo(data, flag);
   } catch (PackageManager.NameNotFoundException e) {
       applicationInformation = null;
   }
   final String applicationName = (String) (applicationInformation != null ? pckManager.getApplicationLabel(applicationInformation) : "(unknown)");
   return applicationName;

}
查看更多
美炸的是我
5楼-- · 2019-01-01 08:58

If you use gradle build, use this: BuildConfig.APPLICATION_ID to get the package name of the application.

查看更多
呛了眼睛熬了心
6楼-- · 2019-01-01 09:00
PackageInfo pinfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
         String sVersionCode = pinfo.versionCode; // 1
         String sVersionName = pinfo.versionName; // 1.0
         String sPackName = getPackageName(); // cz.okhelp.my_app
         int nSdkVersion = Integer.parseInt(Build.VERSION.SDK); 
         int nSdkVers = Build.VERSION.SDK_INT; 

Hope it will work.

查看更多
孤独寂梦人
7楼-- · 2019-01-01 09:03

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

Example: String PackageName = BuildConfig.APPLICATION_ID;

查看更多
登录 后发表回答