How to Get Current Flavor in Gradle

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

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.

How to get Current Build Type in Gradle

You can get the exact build type by parsing your applicationVariants:

applicationVariants.all { variant ->
buildType = variant.buildType.name // sets the current build type
}

A implementation could look like the following:

def buildType // Your variable

android {
applicationVariants.all { variant ->
buildType = variant.buildType.name // Sets the current build type
}
}

task myTask{
// Compare buildType here
}

Also you can check this and this similar answers.

Update

This answer by this question helped the questioner to settle the problem.

Get product flavor or build variant in an android app

Edit: This is now done automatically starting with version 0.7 of the plugin. BuildConfig.java will contains

public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "f1Fa";
public static final String FLAVOR_group1 = "f1";
public static final String FLAVOR_group2 = "fa";

FLAVOR is the combined flavor name with all flavor dimensions/groups applied. Then each dimension is available as FLAVOR_<group name>.

Finally BUILD_TYPE contains the name of the used build type.

If you have a single flavor dimension, then you only have the FLAVOR constant.

This is the only way to do it right now.

One thing you could do is automate it. So you could do something like this:

android {
productFlavors.whenObjectAdded { flavor ->
flavor.buildConfig "public static final String PRODUCT_FLAVOR = \"${flavor.name}\";"
}

// your normal config here.
}

This way you don't have to manually do it for each flavor.



Related Topics



Leave a reply



Submit