Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Running Android Flavor Name in gradle script

This time I have this problem, I am trying to get the current flavor in a gradle script. I have tried the answers given here How to get current flavor in gradle without luck.

I haven seen in some answers that they use

// Get all flavors
android.productFlavors.all { flavor ->
if (flavor.name.equals("flavorName")) {
    // do what you like
}
// ...
}

But also I didn't have any luck with that because i get the following error: > Could not get unknown property 'android' for task

So I don't know how to get the current flavor, any help will be very appreciated thanks!!!

EDIT: What I need to do is to execute a piece of code that is diferent for each flavor, my current idea is to know the selected build variant to do this in a task, but if there is any othe way to do this would be perfect.

like image 399
acabezas Avatar asked Nov 21 '25 09:11

acabezas


1 Answers

I already posted a working solution here, that is:

The following function returns exactly the current flavor name:

def getCurrentFlavor() {
    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(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.

like image 105
Poiana Apuana Avatar answered Nov 24 '25 00:11

Poiana Apuana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!