Gradle: How to apply Flavors for Build Types in Android Studio

Gradle Logo

Gradle is well-known as a central build automation system used in Android Studio IDE developed by Google. To create multiple versions of your application, you would need to modify your app, recompile it and then repeat the procedure with a new version again! This will get messy pretty fast. Thanks to Gradle, getting multiple versions of our app has become extremely easy.

Gradle automatizes the configuration process for every new version of your app in an easy way. Gradle calls it Flavors. To make a long story short, each Flavor is a decorator for an app (e.g. different strings, images or other resources). Gradle also offers Build Types, which do make your app compile in DEBUG or RELEASE mode. The Flavors and Build Types define Build Variants. Each Build Variant generates a modified version of your app (e.g. demo and full/payed versions).

Today I will show you how to combine a Flavor and a Build Type. Below you will find an example of a build.gradle config.

apply plugin: 'com.android.application'

android {
  compileSdkVersion 23
  buildToolsVersion "23.0.1"
  defaultConfig {
  applicationId "com.example.app"
  minSdkVersion 16
  targetSdkVersion 23
  versionCode 1
  versionName "1.0"
}
productFlavors {
  demo {
    applicationId 'com.example.app.demo'
    versionName '1.0 demo'
  }
  full {
    applicationId 'com.example.app.full'
    versionName '1.0 full'
  }
}
buildTypes {
  release {
    debuggable false
    minifyEnabled false
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    productFlavors.demo.buildConfigField "String", "BASE_API_URL", "\"https://your_demo_release_url\""
    productFlavors.full.buildConfigField "String", "BASE_API_URL", "\"https://your_full_release_url\""
  }
  debug {
    debuggable true
    minifyEnabled false
    productFlavors.demo.buildConfigField "String", "BASE_API_URL", "\"https://your_demo_debug_url\""
    productFlavors.full.buildConfigField "String", "BASE_API_URL", "\"https://your_full_debug_url\""
  }
}

As you can see, demo Flavor has two BASE_API_URL defined in DEBUG and RELEASE Build Types. To be able to use it in your source code, you just need to build your project and then to write this (somewhere in your code): BuildConfig.BASE_API_URL — this will allow you to keep your constant defined in a build.gradle file.

!!! CAUTION: Please, note the quotes in the definition section of the config file above. If you forget the quotes, you will end up in a generated BuildConfig file with a String constant which has no quotes (not a valid String constant).

Contents