android - 是否可以将 Java 字符串常量传递给 Gradle 文件?

标签 android kotlin android-gradle-plugin

我正在使用 buildConfigField 将调试和发布服务器 Ip 和其他字符串文字传递到应用程序中。

像这样:

 buildTypes {
        debug {
            buildConfigField "String", "url", "\"http:\\xxxxxxx.xx\""
        }

        release {
            buildConfigField "String", "url", "\"http:\\ppppppp.xx\""
        }
    }

但我遇到了一个问题,即我的应用程序在 Debug模式下可以与多个测试服务器通信。有时我将它指向我的本地网络 Ip,如果我不在工作场所,我将它指向远程测试服务器。

我现在面临的问题是,每当我想更改配置时,我都必须在此处键入完整的 IP 地址:

 debug {
     buildConfigField "String", "url", "\"http:\\xxxxxxx.xx\""
 }

我有一个 Kotlin 文件,其中已经定义了这些 IP 地址:

object API {
    const val URL_MAIN = "http://19.544...."
    const val URL_TEST_LOCAL = "http://192.16...."
    const val URL_TEST_REMOTE = "http://19.554...."
}

有没有办法通过 gradle 文件访问这个变量而不是输入它。

编辑: 我将这些 url 放在 Kotlin 类中,因为我也需要在我的项目中使用它的值。

最佳答案

你不需要为此使用 java 字符串,Product flavors 是完美的解决方案

在你的 Gradle 文件中的 android block 中像这样使用它

productFlavors {

       main {
            dimension "app"
            buildConfigField 'String', 'url', 'http://XXXXXXX'
        }

      test_local {
            dimension "app"
            buildConfigField 'String', 'url', 'http://XXXXXXX'
        }

       test_remote {
            dimension "app"
            buildConfigField 'String', 'url', 'http://XXXXXXX'
        }


    }

使用 Android Studio 左下角的 Build Variant 部分 并选择你想要制作的版本

关于android - 是否可以将 Java 字符串常量传递给 Gradle 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57004407/

相关文章:

Android PopupWindow 动画不工作

android:通过套接字传输文件

android - 在 Kotlin 中设置 Android 监听器 - 在 lambda 中使用 return

android - CircleCI 使用绝对路径,而不是相对路径

android - 如何使用 MediaSession.setMediaButtonReceiver(PendingIntent) 恢复播放

屏幕关闭时非工作传感器的 Android 解决方法

android - 带有 Gradle 错误的 Cordova 6.1.0

android - 与 GoogleServices 插件并行使用 Android DataBinding 插件

spring-boot - 未提供连接字符串(Azure Application Insights)

spring-boot - Gradle、Kotlin、多模块项目 : Getting build errors while compiling this project