首页 > 解决方案 > 如何在 Kotlin 中为环境设置不同的常量

问题描述

我们在 Kotlin(Android Stdio)中有一个应用程序,它具有不同的环境常量。我们正在使用 Constants.kt const val IMAGES_API = "https://localhost:3000/v1/images" 并且我们希望在 staging/qa/prod 中使用相同的变量。该应用程序是在 Kotlin 中构建的,我们正在使用 gradle(groovy 脚本)来编译和打包不同的环境 staging/qa/prod。我的第一种方法是在 gradle.properties 上创建此属性并在 build.gradle 文件中加载这些属性,如下所示:

def loadProperties() {
def props = new Properties()
file("gradle.properties").withInputStream { props.load(it) }
def config = props
project.ext.config = config
}

当我运行 gradle 时,我可以看到新属性,但我不知道如何在 App 中获取这个值(在 kotlin 代码中)。

我唯一的想法是在 build.gradle 上创建一个任务来按环境复制一个 Constants.kt 文件。但是,我不认为,这是一个好习惯。我认为,必须有另一种方法来在 App 中设置不同的变量。请问,有人可以帮我解决这个问题吗?

标签: androidperformanceandroid-studiokotlingradle

解决方案


您想要的是在您的应用程序模块的 gradle 文件中配置构建类型buildConfigField

 buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

            buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
        }

        debug {
            applicationIdSuffix ".debug"
            debuggable true

            buildConfigField "String", "SERVER_URL", '"http://test.this-is-so-fake.com"'
        }

        /**
         * The `initWith` property allows you to copy configurations from other build types,
         * then configure only the settings you want to change. This one copies the debug build
         * type, and then changes the application ID.
         */
        staging {
            initWith debug
            applicationIdSuffix ".debugStaging"

            buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
        }
    }

在代码中,您可以参考BuildConfig.SERVER_URL,它将根据您在编译时选择的构建类型填充字符串。

您可以构建不同的 apk/app 捆绑包进行分发。

参考这个答案

编辑顺便说一句,在现实生活中,我发现这种方法很……烦人。在应用程序内部捆绑一个允许 QA 在环境之间切换的切换更容易。这样,您只需处理一个捆绑包。


推荐阅读