我知道Context.getApplicationContext()和View.getContext()的可用性,通过它们我实际上可以调用Context.getPackageName()来检索应用程序的包名。

如果我从一个View或Activity对象可用的方法中调用,它们就可以工作,但是如果我想从一个完全独立的没有View或Activity的类中找到包名,有没有办法(直接或间接地)做到这一点?


当前回答

如果你使用gradle-android-plugin来构建你的应用程序,那么你可以使用

BuildConfig.APPLICATION_ID

从任何作用域(包括静态作用域)检索包名。

其他回答

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;

}

如果你使用gradle build,使用这个:BuildConfig。APPLICATION_ID获取应用程序的包名。

你可以使用未记录的方法android.app.ActivityThread.currentPackageName():

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

注意:这必须在应用程序的主线程中完成。

感谢这篇博客文章的想法:http://blog.javia.org/static-the-android-application-package/。

只需使用这段代码

val packageName = context.packageName 

如果你使用gradle-android-plugin来构建你的应用程序,那么你可以使用

BuildConfig.APPLICATION_ID

从任何作用域(包括静态作用域)检索包名。