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

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


当前回答

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

其他回答

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

这适用于我在kotlin

       override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       
        var packageName=applicationContext.packageName // need to put this line
        Log.d("YourTag",packageName)
}

只需使用这段代码

val packageName = context.packageName 
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;

}

只需导入Android。App,然后你可以使用: < br / > Application.getProcessName () < br / >

获取不包含上下文、视图或活动的当前应用程序进程名。