Gradle Build Variables – How To Create Build Level Variables

In an Android Project, by default we have 2 build types. They are release and debug types.

As its name suggests, release type builds are for publishing the app in Google Play Store and debug type builds are for debugging purpose i.e, builds generated during development process.

There are some values like package id, app name, constants, build level flags etc are different for debug and release builds. How do we change these build based values to the app? It is not wise option to create two separate source code for these values.

Creating app’s variables through build scripts is the solution. If we create variables under build.gradle file’s buildTypes then we can provide different values based on its build type.

That is, let’s say your application is being deployed into two environments. One is staging and other is production. As environment changes, there will be a change in variables also. How do we do achieve this changes?

Gradle build system enables us to do this by giving options to write variables values different for each build varient.

Please see the example gradle script below,

buildTypes {
  release {
     buildConfigField "int", "FOO", "100"
     buildConfigField "boolean", "reportCrashes", "true"
     buildConfigField "boolean", "allowLogs", "false"
     buildConfigField "String", "BASE_URL", "\"\""
     resValue "string", "appName", "DevDeeds"
  debug {
     buildConfigField "int", "FOO", "101"
     buildConfigField "boolean", "reportCrashes", "false"
     buildConfigField "boolean", "allowLogs", "true"
     buildConfigField "String", "BASE_URL", "\"\""
     resValue "string", "appName", "Beta-DevDeeds"

In the above example, the following line will create a build level variable,

  buildConfigField "boolean", "reportCrashes", "false" 

This variable is accessible at the runtime as shown below,

  if (BuildConfig.reportCrashes) {

We can create variables of type Integer, Boolean and String using Gradle script.

Here what we have done is, we have allowed crash reporting only in release build variant.

This solution help us to use the same source code in debug and release builds.

About author

Rojer is a programmer by profession, but he likes to research new things and is also interested in writing. Devdeeds is his blog, where he writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *