How to get Running Android Flavor Name in gradle script

北战南征 提交于 2020-01-04 05:40:06

问题


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.


回答1:


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.




回答2:


You can get this error if your use it out of "android" closure at app level gradle script. Make sure that you use it inside



来源:https://stackoverflow.com/questions/40528970/how-to-get-running-android-flavor-name-in-gradle-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!