dleerob dleerob - 4 years ago 292
Android Question

How do I set an environment variable in Android Studio before it runs my gradle build

My Gradle build looks at an environment variable called BUILD_NUMBER to determine the version to allocate to my android application as follows:

def buildNumber = System.getenv("BUILD_NUMBER") ?: "local"


So as long as that environment variable is set, the build number is used in defaultConfig as follows:

versionName "1.4.0."+buildNumber


Usually, Jenkins will call this Gradle build and supply the BUILD_NUMBER environment variable.

If I run the Gradle build from my command prompt, I know I can set BUILD_NUMBER = x.

However, if I build using Android Studio, how can I set the BUILD_NUMBER environment variable through Android Studio itself?

Answer Source

I ended up using the following in my build.gradle:

def buildNumber = System.getenv("BUILD_NUMBER")
if (buildNumber == null) {
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    buildNumber = properties.getProperty('buildNumber')?:"NoBuildNumberFound"
}

Because the local.properties file is not supposed to be committed to your source code repository, each developer manages their own copy.

So if they want to set the buildNumber on their local Android Studio, they simply add the following to their local.properties:

buildNumber=7

So on a local developers machine, the build number will be set to what ever they put into their local.properties file, but on our Jenkins server, it will use the environment variable BUILD_NUMBER

Our Jenkins server sets the BUILD_NUMBER environment variable

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download