我想在应用程序的外围实例化 Retrofit,在实现需要某些网络库来执行 API 调用的接口(interface)的类中。
我想将 App Version 作为自定义 header 添加到我所有的 Retrofit 请求中,这可以在 Retrofit 实例化时完成。
我无法在那里访问 Context,我希望能够以某种方式动态获取应用程序版本(无需每次都对其进行硬编码)而不需要 Context。
或者也许我应该将上下文传递给所选的网络库?
我只知道使用上下文获取应用程序版本的一种方法:
private static String getAppVersion(Context context) {
String appVersion = "";
try {
if (context != null) {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
if (pInfo != null) {
appVersion = pInfo.versionName;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return appVersion;
} // End of getAppVersion
最佳答案
如果您使用的是 Gradle/Android Studio,您可以通过以下方式静态获取它
int verCode = BuildConfig.VERSION_CODE;
String verName = BuildConfig.VERSION_NAME;
关于android - 如何在不使用上下文的情况下动态获取应用程序版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34131941/