86

I have two product flavors for my app:

productFlavors {
    europe {
        buildConfigField("Boolean", "BEACON_ENABLED", "false")
    }

    usa {
        buildConfigField("Boolean", "BEACON_ENABLED", "true")
    }
}

Now I want to get the current flavor name (which one I selected in Android Studio) inside a task to change the path:

task copyJar(type: Copy) {
    from('build/intermediates/bundles/' + FLAVOR_NAME + '/release/')
}

How can I obtain FLAVOR_NAME in Gradle?

Thanks

7
  • There is no "current flavor". The Gradle build file is building an object model of the build process. It is not an interpreted script only being used once a build is underway and a "current flavor" is known. Commented Jun 3, 2015 at 13:38
  • 2
    There must be a way to retrieve that value because it changes paths in buildDir. Commented Jun 3, 2015 at 14:02
  • You do what azertiti's answer shows: configure all the build variants. Commented Jun 3, 2015 at 14:05
  • 13
    @CommonWare You keep telling people this. What about using android Studio with Gradle makes people think that their task should be able to know what value is currently selected and able to be used by a task AFTER Gradle has built its model up. The question is flawed yes, its not Gradle if you want to be pedantic seeing your responses to this is comical now, so take that vast Gradle knowledge and looking beyond the pedantic short comings of the question, how does a task, defined inside a .gradle file, know what variant is selected when the task/command is run? That is the question I believe.\o/ Commented May 20, 2016 at 18:43
  • 1
    @CommonsWare (I'm not saying your response is comical btw!!! In reread my comment comes off 'possibly' attackish. Which is not the intent. It's just such a common frustration in learning Gradle integration into Android Studio to be interpret/expect state since its 'got code in it' as such it has become comical to me now. :P I've read it a 100 times, but until I wrestled it head on and came to terms with it I don't know if most folks will understand until that wall is hit head on. Commented May 20, 2016 at 18:58

13 Answers 13

112

How to get current flavor name

I have developed the following function, returning exactly the current flavor name:

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String  tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern

    if( tskReqStr.contains( "assemble" ) ) // to run ./gradlew assembleRelease to build APK
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else if( tskReqStr.contains( "bundle" ) ) // to run ./gradlew bundleRelease to build .aab
        pattern = Pattern.compile("bundle(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher( tskReqStr )

    if( matcher.find() )
        return matcher.group(1).toLowerCase()
    else
    {
        println "NO MATCH FOUND"
        return ""
    }
}

You need also

import java.util.regex.Matcher
import java.util.regex.Pattern

at the beginning or your script. In Android Studio this works by compiling with "Make Project" or "Debug App" button.

How to get current build variant

def getCurrentVariant() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern

    if (tskReqStr.contains("assemble"))
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher(tskReqStr)

    if (matcher.find()){
        return matcher.group(2).toLowerCase()
    }else{
        println "NO MATCH FOUND"
        return ""
    }
}

How to get current flavor applicationId

A similar question could be: how to get the applicationId? Also in this case, there is no direct way to get the current flavor applicationId. Then I have developed a gradle function using the above defined getCurrentFlavor function as follows:

def getCurrentApplicationId() {
    def currFlavor = getCurrentFlavor()

    def outStr = ''
    android.productFlavors.all{ flavor ->

        if( flavor.name==currFlavor )
            outStr=flavor.applicationId
    }

    return outStr
}

Voilà.

Sign up to request clarification or add additional context in comments.

18 Comments

is there a possibility to get current flavor applicationId?
@Igor: I think you have not understood at all what the script does. Many developers use this script everyday to get the current flavor. There is no direct way to get the current flavor; the call getGradle().getStartParameter().getTaskRequests() gives something like generateEuropeDebugSources or generateEuropeReleaseSources (if europe is the current flavor) depending on the current build type; then the Pattern class extracts the flavor name, not build type. Before replying, please study what the Pattern class does in the script.
Where should I call this function in the file gradle.build? If I try to call it for selectively applying some plugin it doesn't work.
@AlirezaNoorali you can call getCurrentFlavor() in a task in build.gradle. See guides.gradle.org/writing-gradle-tasks to learn about gradle tasks.
This doesn't seem to work if "gradlew build" is run from the command line. tskReqStr is [DefaultTaskExecutionRequest{args=[build],projectPath='null'}]. Works fine if building from Android Studio
|
29

I use this

${variant.getFlavorName()}.apk

to format file name output

Comments

14

you should use this,${variant.productFlavors[0].name},it will get productFlavors both IDE and command line.

2 Comments

How can I get variant variable in concrete flavor block?
This snippet depends on nesting inside a applicationVariants.all { variant -> loop. This returns the first flavor, which is only relevant when performing a single output build.
8

I slightly changed Poiana Apuana's answer since my flavor has some capital character.

REASON
gradle.getStartParameter().getTaskRequests().toString() contains your current flavor name but the first character is capital.
However, usually flavor name starts with lowercase. So I forced to change first character to lowercase.

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String taskReqStr = gradle.getStartParameter().getTaskRequests().toString()
    Pattern pattern
    if (taskReqStr.contains("assemble")) {
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    } else {
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
    }
    Matcher matcher = pattern.matcher(taskReqStr)
    if (matcher.find()) {
        String flavor = matcher.group(1)
        // This makes first character to lowercase.
        char[] c = flavor.toCharArray()
        c[0] = Character.toLowerCase(c[0])
        flavor = new String(c)
        println "getCurrentFlavor:" + flavor
        return flavor
    } else {
        println "getCurrentFlavor:cannot_find_current_flavor"
        return ""
    }
}

1 Comment

Can you please tell me why I am getting value of gradle.getStartParameter().getTaskRequests().toString() as empty i.e. [ ] in my app's build.gradle ?
7

This is what I used some time ago. I hope it's still working with the latest Gradle plugin. I was basically iterating through all flavours and setting a new output file which looks similar to what you are trying to achieve.

applicationVariants.all { com.android.build.gradle.api.ApplicationVariant variant ->
    for (flavor in variant.productFlavors) {
        variant.outputs[0].outputFile = file("$project.buildDir/${YourNewPath}/${YourNewApkName}.apk")
    }
}

Comments

6

my solution was in that to parse gradle input parameters.

Gradle gradle = getGradle()

Pattern pattern = Pattern.compile(":assemble(.*?)(Release|Debug)");
Matcher matcher = pattern.matcher(gradle.getStartParameter().getTaskRequests().toString());
println(matcher.group(1))

1 Comment

java.lang.IllegalStateException: No match found
5

get SELECTED_BUILD_VARIANT from the .iml file after gradle sync completes You can either load it using an xml parser, or less desireable, but probably faster to implement would be to use a regex to find it.

<facet type="android" name="Android">
  <configuration>
    <option name="SELECTED_BUILD_VARIANT" value="your_build_flavorDebug" />
        ...

(not tested, something like this:)

/(?=<name="SELECTED_BUILD_VARIANT".*value=")[^"]?/

Comments

4

Use:

${variant.baseName}.apk"

This return current flavor name

Full Answer

android.applicationVariants.all { variant ->
    variant.outputs.all {
        outputFileName = "${variant.baseName}.apk"
    }
}

Comments

2

You can use gradle.startParameter.taskNames[0]

3 Comments

gradle.startParameter.taskNames[0].contains("debug") - Cannot invoke method contains() on null object
This fails on Sync, so must be wrapped in some if.
didn't work as expected, because you can call ./gradlew aD for "flavor" assembleDebug, and in that case returned flavor is aD not assembleDebug.
2

Just add the following in your build.gradle (app level)

def getCurrentFlavour() {
  Gradle gradle = getGradle()
  String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
  print(tskReqStr.toString())

  Pattern pattern;
  if( tskReqStr.contains( "assemble" ))
    pattern = Pattern.compile("assemble(\\w+)(Release|Staging|Debug)")
  else
    pattern = Pattern.compile("generate(\\w+)(Release|Staging|Debug)")
  Matcher matcher = pattern.matcher( tskReqStr )
  if( matcher.find() ) {
    def value = matcher.group(1).toLowerCase()
    return value
  } else {
    return "";
  }
}

Now Inside android tag,

android {  
// android tag starts
 defaultConfig {
  - - - - - - - - 
  - - - - - - - - 
 }
 - - - - - - - - 
 - - - - - - - - 
 
 def flavourName = getCurrentFlavour()
  if (flavourName == "Dev") {
    println("This is Dev")
   } else if (flavourName == "Staging") {
    println("This is Staging")
   } else if (flavourName == "Production") {
    println("This is Production")
   } else {
    println("NA")
   }
// android tag ends
}

Now Sync & Build your project.

Comments

1

A combination of aforementioned snippets was needed for me to get this to work.

My full answer to the original question would look like this:

android {
    ...
    applicationVariants.all { variant ->
        task "${variant.getName()}CopyJar"(type: Copy) {
            from("build/intermediates/bundles/${variant.getFlavorName()}/release/")
        }
    }
}

This creates a <variant>CopyJar task for each variant, which you can then run manually.

Comments

0

How to get the flavor name or build variant from a prebuild task? This is what solved my issue. I added getCurrentFlavor() or getCurrentVariant() (from @Poiana Apuana answer) into my task's dependOn like so:

task getCurrentFlavor() {
    // paste Poiana Apuana's answer
}

// OR
//task getCurrentVariant() {
//  // paste Poiana Apuana's answer
//}

task myTask(type: Copy) {
    dependsOn getCurrentFlavor
    // or dependsOn getCurrentVariant
    println "flavor name is $projectName"
    ...
}
preBuild.dependsOn myTask

Check original problem here.

Comments

0

Here is the "official" getFlavour() function you may find in react-native-config package. Probably it's most accurate.

def getCurrentFlavor() {
    Gradle gradle = getGradle()

    // match optional modules followed by the task
    // (?:.*:)* is a non-capturing group to skip any :foo:bar: if they exist
    // *[a-z]+([A-Za-z]+) will capture the flavor part of the task name onward (e.g., assembleRelease --> Release)
    def pattern = Pattern.compile("(?:.*:)*[a-z]+([A-Z][A-Za-z0-9]+)")
    def flavor = ""

    gradle.getStartParameter().getTaskNames().any { name ->
        Matcher matcher = pattern.matcher(name)
        if (matcher.find()) {
            flavor = matcher.group(1).toLowerCase()
            return true
        }
    }

    return flavor
}

1 Comment

didn't work as expected, because you can call ./gradlew aD for "flavor" assembleDebug, and in that case returned flavor is aD not assembleDebug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.