Skip to content

Latest commit

 

History

History

addCustomBuildConfigFields

Adding dynamic BuildConfig fields through the Variant API.

This recipe show how to add BuildConfig with dynamic values. One value is obtained from a function call, the other value is obtained from a task output.

Module Content
build-logic Contains the Project plugin that is the core of the recipe.
app An Android application that will be configured with the BuildConfig fields.

Details

Turning on BuildConfig.

Starting in Android Gradle Plugin 8.0, the BuildConfig fields are not generated by default and one need to turn on the feature by specifying :

buildFeatures {
    buildConfig = true
}

Adding Fields.

Adding fields for a specific Variant can be done by adding an element to the buildConfigFields map.

From a function execution

Adding fields for a specific Variant can be done by using AndroidComponentsExtension.selector but in this case, the fields are added to all variants :

androidComponents.onVariants { variant: Variant ->
    variant.buildConfigFields.put("FloatValue",
        BuildConfigField(
            type = "Float",
            value = "${calculateFloatValue()}f",
            comment = "Float Value")
    )
 }

Note that the example is adding different fields in the debug and release variants, therefore the source files using those fields are also located in the build-type specific source folder.

From a Task execution

The map can take a Provider as a value which allow you to easily map the output value of a Task. By mapping the output value, the Task identified by gitVersionProvider will execute before the map is queried at execution time. The Task will write relevant information to an output file which is read in the mapping code below.

androidComponents.onVariants { variant: Variant ->
    variant.buildConfigFields.put(
        "GitVersion", 
        gitVersionProvider.map {  task ->
                BuildConfigField(
                    type = "String",
                    value = "\"{task.gitVersionOutputFile.get().asFile.readText(Charsets.UTF_8)}\"",
                    comment = "Git Version")
        }
    )
}

Remember to use AndroidComponentsExtension.selector to filter out the un-needed Variant.

Run the example

To run the examples, you can just do:

./gradlew assembleDebug

and the build should be successful as the added BuildConfig fields are used in the MainActivity.kt