【问题标题】:How to read android app info without context from a module?如何在没有上下文的情况下从模块中读取 android 应用程序信息?
【发布时间】:2018-07-10 08:03:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: android android-context


    【解决方案1】:

    在数据层中有上下文是可以的。但是复制代码是不行的。因此,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())
    }}
    

    【讨论】:

      【解决方案2】:

      制作以这种方式返回版本名称的方法并将方法传递给被调用的网络..

      public String getVersionName(){
      
          PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
          String versionname = pinfo.versionName;
          return versionname;
      }
      

      【讨论】:

      • 这不是解决方案。如果我传递一个使用上下文的函数,我可以传递上下文。我不想将上下文传递给调用网络并实现应用程序业务逻辑的复杂模块。
      • 然后将此信息存储到 sharedPreference 并在任何地方访问它。
      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 2020-09-28
      • 2015-11-18
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      相关资源
      最近更新 更多