是否可以将Java字符串常量传递给Gradle文件? [英] Is it possible to pass Java String Constants to Gradle file?

查看:82
本文介绍了是否可以将Java字符串常量传递给Gradle文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用buildConfigField传递调试信息并将服务器IP和其他字符串文字发布到应用中.

I'm using buildConfigField to pass debug and release server Ip and other string literals into app.

像这样:

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

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

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

But i'm having an issue that My app can communicate with multiple test servers when debug mode. Some times I point it to my local network Ip and if i'm not in workplace, I point it to a remote test server.

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

The issue that i'm facing right now is that I have to Type entire IP address here whenever I wanted to change configuration :

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

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

I have a Kotlin file with these Ip address already defined:

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文件访问此变量,而不用键入它.

Is there anyway to access this variable through gradle file instead of typing it.

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

推荐答案

您无需为此使用Java字符串,产品版本是完美的解决方案

You don't need to use java strings for this, Product flavors are the perfect solution

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

in your android block in Gradle file use it like this

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部分 然后选择您要建造的建筑物

Use Build Variant section from the bottom left corner of Android studio and choose which build you want to make

这篇关于是否可以将Java字符串常量传递给Gradle文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆