Android – How to set an environment variable in Android Studio before it runs the gradle build

androidandroid-gradle-pluginandroid-studiogradle

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?

Best Answer

One option is to make use of gradle properties that can be overriden by environment variables. You can read about it here.

If the environment variable name looks like ORG_GRADLE_PROJECT_prop=somevalue, then Gradle will set a prop property on your project object, with the value of somevalue.

What this means is that you can

  1. set BUILD_NUMBER=42 in your .properties file (project, or global) as you would usually do,
  2. and in your CI you would name the environment variable ORG_GRADLE_PROJECT_BUILD_NUMBER, overwriting or setting BUILD_NUMBER in your CI build.

Note: Use gradle.properties in your project root directory, and do not modify local.properties.