Using Build Configs to Change Variables in Android Studio

May 12, 2019

In Android Studio it is possible define a “Build flavor” to set variables for different configurations of an app.  By default there is already 2 build type, release and debug which can be used to store variables but release has certain restrictions preventing it being used for quick debugging. The solution to this is to create multiple build flavors with a debug and release variants that store the unique settings.

productFlavors {
    local {
        ext {
            variable = [debug: "192.168.1.21", release: "productionurl.com"]
        }
    }
    cloud {
        ext {
            variable = [debug: "productionurl.com", release: "productionurl.com"]
        }
    }
}
flavorDimensions 'serverURL'

applicationVariants.all { variant ->
    def flavor = variant.productFlavors[0]
    variant.buildConfigField "String", "BASEURL", "\"${flavor.variable[variant.buildType.name]}\""
}

 

The code above is defining the local and cloud build types. This is building done in the module level (displayed as something other than ‘application’) `build.gradle` file. The only variable being the “BASE_URL”. This will be “productionurl.com” in both release versions but will be “192.168.1.21” only on the local build type.

And in the project this variable can be access as such
private  static final String BASE_URL = BuildConfig.BASEURL;

This post was originally written by Conner Wallace in May, 2019