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

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


当前回答

如果你的意思是没有一个明确的Context(例如来自后台线程),你应该在你的项目中定义一个类:

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();
    }
}

然后在清单中,您需要将这个类添加到Application选项卡的Name字段中。或者编辑xml并放置

<application
    android:name="com.example.app.MyApp"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    .......
    <activity
        ......

然后你可以在任何地方打电话

String packagename= MyApp.getContext().getPackageName();

希望能有所帮助。

其他回答

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; 

希望它能起作用。

你可以使用未记录的方法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/。

这适用于我在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)
}
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获取应用程序的包名。