Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time
None of the above answers gave me any guidelines so I had to spend two hours learning about Groovy Methods.
I wanted be able to go against a production, sandbox and local environment. Because I'm lazy, I only wanted to change the URL at one place. Here is what I came up with:
flavorDimensions 'environment'
productFlavors {
production {
def SERVER_HOST = "evil-company.com"
buildConfigField 'String', 'API_HOST', "\"${SERVER_HOST}\""
buildConfigField 'String', 'API_URL', "\"https://${SERVER_HOST}/api/v1/\""
buildConfigField 'String', 'WEB_URL', "\"https://${SERVER_HOST}/\""
dimension 'environment'
}
rickard {
def LOCAL_HOST = "192.168.1.107"
buildConfigField 'String', 'API_HOST', "\"${LOCAL_HOST}\""
buildConfigField 'String', 'API_URL', "\"https://${LOCAL_HOST}/api/v1/\""
buildConfigField 'String', 'WEB_URL', "\"https://${LOCAL_HOST}/\""
applicationIdSuffix ".dev"
}
}
Alternative syntax, because you can only use ${variable}
with double quotes in Groovy Methods.
rickard {
def LOCAL_HOST = "192.168.1.107"
buildConfigField 'String', 'API_HOST', '"' + LOCAL_HOST + '"'
buildConfigField 'String', 'API_URL', '"https://' + LOCAL_HOST + '/api/v1/"'
buildConfigField 'String', 'WEB_URL', '"https://' + LOCAL_HOST + '"'
applicationIdSuffix ".dev"
}
What was hard for me to grasp was that strings needs to be declared as strings surrounded by quotes. Because of that restriction, I couldn't use reference API_HOST
directly, which was what I wanted to do in the first place.
How can you insert String result of function into buildConfigField
Here's an example of build date in human-readable format set:
def getDate() {
return new SimpleDateFormat("dd MMMM yyyy", new Locale("ru")).format(new Date())
}
def buildDate = getDate()
defaultConfig {
buildConfigField "String", "BUILD_DATE", "\"$buildDate\""
}
You can create build config field overridable via system environment variables during build:
Fallback is used while developing, but you can override the variable when you run the build on Jenkins or another tool.
In your app build.gradle:
buildTypes {
def serverUrl = '\"' + (System.getenv("SERVER_URL")?: "http://default.fallback.url.com")+'\"'
debug{
buildConfigField "String", "SERVER_URL", serverUrl
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "SERVER_URL", serverUrl
}
}
The variable will be available as BuildConfig.SERVER_URL
.