Android Gradle for Android Define and use Build Configuration Fields

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

BuildConfigField

Gradle allows buildConfigField lines to define constants. These constants will be accessible at runtime as static fields of the BuildConfig class. This can be used to create flavors by defining all fields within the defaultConfig block, then overriding them for individual build flavors as needed.

This example defines the build date and flags the build for production rather than test:

android {
    ...
    defaultConfig {
        ...
        // defining the build date
        buildConfigField "long", "BUILD_DATE", System.currentTimeMillis() + "L"
        // define whether this build is a production build
        buildConfigField "boolean", "IS_PRODUCTION", "false"
        // note that to define a string you need to escape it
        buildConfigField "String", "API_KEY", "\"my_api_key\""
    }

    productFlavors {
        prod {
            // override the productive flag for the flavor "prod"
            buildConfigField "boolean", "IS_PRODUCTION", "true"
            resValue 'string', 'app_name', 'My App Name'
        }
        dev {
            // inherit default fields
            resValue 'string', 'app_name', 'My App Name - Dev'
        }
    }
}

The automatically-generated <package_name>.BuildConfig.java in the gen folder contains the following fields based on the directive above:

public class BuildConfig {
    // ... other generated fields ...
    public static final long BUILD_DATE = 1469504547000L;
    public static final boolean IS_PRODUCTION = false;
    public static final String API_KEY = "my_api_key";
}

The defined fields can now be used within the app at runtime by accessing the generated BuildConfig class:

public void example() {
    // format the build date
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    String buildDate = dateFormat.format(new Date(BuildConfig.BUILD_DATE));
    Log.d("build date", buildDate);
    
    // do something depending whether this is a productive build
    if (BuildConfig.IS_PRODUCTION) {
        connectToProductionApiEndpoint();
    } else {
        connectToStagingApiEndpoint();
    }
}

ResValue

The resValue in the productFlavors creates a resource value. It can be any type of resource (string, dimen, color, etc.). This is similar to defining a resource in the appropriate file: e.g. defining string in a strings.xml file. The advantage being that the one defined in gradle can be modified based on your productFlavor/buildVariant. To access the value, write the same code as if you were accessing a res from the resources file:

getResources().getString(R.string.app_name)

The important thing is that resources defined this way cannot modify existing resources defined in files. They can only create new resource values.


Some libraries (such as the Google Maps Android API) require an API key provided in the Manifest as a meta-data tag. If different keys are needed for debugging and production builds, specify a manifest placeholder filled in by Gradle.

In your AndroidManifest.xml file:

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}"/>

And then set the field accordingly in your build.gradle file:

android {
    defaultConfig {
        ...
        // Your development key
        manifestPlaceholders = [ MAPS_API_KEY: "AIza..." ]
    }

    productFlavors {
        prod {
            // Your production key
            manifestPlaceholders = [ MAPS_API_KEY: "AIza..." ]
        }
    }
}

The Android build system generates a number of fields automatically and places them in BuildConfig.java. These fields are:

FieldDescription
DEBUGa Boolean stating if the app is in debug or release mode
APPLICATION_IDa String containing the ID of the application (e.g. com.example.app)
BUILD_TYPEa String containing the build type of the application (usually either debug or release)
FLAVORa String containing the particular flavor of the build
VERSION_CODEan int containing the version (build) number.
This is the same as versionCode in build.gradle or versionCode in AndroidManifest.xml
VERSION_NAMEa String containing the version (build) name.
This is the same as versionName in build.gradle or versionName in AndroidManifest.xml

In addition to the above, if you have defined multiple dimensions of flavor then each dimension will have its own value. For example, if you had two dimensions of flavor for color and size you will also have the following variables:

FieldDescription
FLAVOR_colora String containing the value for the 'color' flavor.
FLAVOR_sizea String containing the value for the 'size' flavor.


Got any Android Question?