artzok
artzok

Reputation: 181

how to get current selected product flavors in app/build.gradle file

Example, I have area1 and area2 flavors, but just area2 have google gms dependency, and I just want apply gms plugin to area2, so I need decide current flavors as area == 'area2', obvious this can't succeed, so how can I to do ?

flavorDimensions "area"
productFlavors {
    area1 {
        dimension "area"
        applicationId 'com.sample.area1'
    }
    area2 {
        dimension "area"
        applicationId 'com.sample.area2'
    }
}
dependencies {
   area2Implementation 'com.google.android.gms:play-services-auth: 16.0.1'
}
if(area == 'area2') {
  apply plugin: 'com.google.gms.google-services'
}

Upvotes: 4

Views: 6656

Answers (2)

Wei WANG
Wei WANG

Reputation: 1776

Just add the following android.applicationVariants.all configuration in your Android block:

android {

    // Flavor definitions here
    productFlavors {
        // ...
    }

    android.applicationVariants.all { variant ->

        if (variant.flavorName == "area2") {
            apply plugin: 'com.google.gms.google-services'
        }
    }
}

==== Updated 7/1/2019 ====

Just realize the above block of android.applicationVariants.all is executed for all build variants each time (i.e. if you have 2 build types plus 3 flavors it will be hit by all of the 6 variants). And it's actually to prepare different configurations for individual variants to build later.

So in order to achieve the purpose we need to apply the plugin during the build phase. Not sure if there's a better way but I managed to do something tricky like:

if (getGradle().getStartParameter().getTaskRequests().toString().contains("Area2")) {
    apply plugin: 'com.google.gms.google-services'
}

I put this at the end of the Gradle file, out of the Android block (where the "apply plugin" block originally is). Also note that you need to have your flavor keyword's first character in upper case because it's part of the task name string like [:app:assembleArea2Debug]] if you use println to check it out in gradle console.

Upvotes: 4

artzok
artzok

Reputation: 181

I found a solution:

gradle.taskGraph.whenReady { taskGraph ->
    def tasks = taskGraph.getAllTasks()
        for(task in tasks) {
        if(task.getName().startsWith('assembleArea2')) {
            apply plugin: 'com.google.gms.google-services'
            break
        }
    }
}

Upvotes: 0

Related Questions