android tutorial - Define and use Build Configuration Fields in Android | Developer android - android app development - android studio - android app developement
Define and use Build Configuration Fields
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:
- The automatically-generated
.BuildConfig.java in the gen folder contains the following fields based on the directive above:
The defined fields can now be used within the app at runtime by accessing the generated BuildConfig class:
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:
- 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:
And then set the field accordingly in your build.gradle file:
The Android build system generates a number of fields automatically and places them in BuildConfig.java. These fields are:
Field | Description |
---|---|
DEBUG | a Boolean stating if the app is in debug or release mode |
APPLICATION_ID | a String containing the ID of the application (e.g. com.example.app) |
BUILD_TYPE | a String containing the build type of the application (usually either debug or release) |
FLAVOR | a String containing the particular flavor of the build |
VERSION_CODE | an int containing the version (build) number. This is the same as versionCode in build.gradle or versionCode in AndroidManifest.xml |
VERSION_NAME | a 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:
Field | Description |
---|---|
FLAVOR_color | a String containing the value for the 'color' flavor. |
FLAVOR_size | a String containing the value for the 'size' flavor. |