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. |
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 for a specific Variant can be done by adding an element to the buildConfigFields
map.
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.
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.
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