Search code examples
gradleandroid-gradle-pluginbuild.gradleandroid-flavors

Modifying build.gradle for a particular flavor


I am modifying a build.gradle with specifical code for a single flavor. Specifically, I'm modifying internally this cycle

 project.android.applicationVariants.all { variant ->

Is a best practice to wrap the custom code for johndoe flavor in

if (variant.flavorName.toLowerCase().contains("johndoe")) {

... or there are some drawbacks in this solution?


Solution

  • In short, yes. Android Documentation suggests to use it for variant specific customization when there are multiple flavor dimensions and build type combinations, like in their, example which sets different version codes for different abi variants. It can be easily used for doing something as you're suggesting.

    One thing to look out for is what the "custom code" is doing. The custom code could be configuring the build or would want to add extra steps in the build process or even both! If it is configuration related, then the "custom code" should look like the example above. However if it wants to add extra processing or build logic, then that should be done in the form of a Gradle Task like the below:

    ....
    applicationVariants.all { variant ->
        if (variant.buildType.name == "release") {
            task("customReleaseLogic") {
                description = "Runs some custom release logic"
                // run some custom release logic 
            }
            variant.assemble.dependsOn("customReleaseLogic")
        }
    }
    ....
    

    That way, the Gradle build will know that there is an extra step needed to be done while building the project.