如何在没有上下文的情况下从模块中读取android应用程序信息



在我的android应用程序中,我需要登录到远程服务器并发送有关该应用程序的信息(版本名称、版本代码(。我知道我可以用以下代码阅读这些信息:

PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
String versionname = pinfo.versionName;

我还可以从gradle中读取此信息:"BuildConfig.VERSION_NAME"。问题是登录过程在网络模块中,我不想将上下文作为参数传递给每个网络调用。生成的BuildConfig是相对于模块版本而不是应用程序版本的。

在数据层中有Context是可以的。但重复代码是不可以的。因此,在OkHttp中有一种叫做Interceptor的机制。如果您将其添加到配置OkHttp客户端中,它将应用于每个网络调用。

class ApplicationInfoHeadersInterceptor(context: Context) : Interceptor {
private val appVersion = DeviceUtil.getAppVersionName(context)
private val osVersion = Build.VERSION.RELEASE
private val deviceId = DeviceUtil.getDeviceId(context)
private val applicationId = context.packageName
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder().apply {
header("APP-VERSION", appVersion)
header("OS-VERSION", osVersion)
header("OS", "android")
header("DEVICE-ID", deviceId)
}
return chain.proceed(builder.build())
}}

最新更新