Question

I am trying to set a buildConfigField in my productFlavor block, and then reference that field elsewhere in my gradle build file so that I can use this value when constructing the name for my apk.

e.g

productFlavors{
    flavor1{            
        buildConfigField "String", "APP_FLAVOR_NAME", '"MyApp-Flavor1"'

    }
    flavor2{            
        buildConfigField "String", "APP_FLAVOR_NAME", '"MyApp-Flavor2"'

    }

How can I access APP_FLAVOR_NAME elsewhere in my build.gradle script?

I am also struggling to figure out how to just reference the flavor name itself in the buildscript as another option to constructing the apk name. How can I do that as well?

Was it helpful?

Solution

Adding a buildConfigField writes an entry into your BuildConfig.java file and is not meant to be exposed at the buildscript level. This is a way provide meta-information about a specific build to interested application code -- not other buildscript code. If you want to throw names around at the buildscript level, you'll need to use Gradle properties.

Explicitly, if you want to access the BuildConfigField collection of objects elsewhere in your script, you can with android.productFlavors.flavor1.buildConfigFields.

Edit

To get a specific flavor name when iterating over android.applicationVariants.all, you can iterate over the flavors collection like so (note you don't need to capture the reference to the item you are iterating over, but it is instructive to see what objects you are actually accessing):

task printFlavors << {
    println "BuildTypes ⨯ Flavors:"
    android.applicationVariants.all { variant ->
        println name
        variant.productFlavors.each { flavor ->
            println flavor.name
        }
    }
}

Or, as suggested by kcoppock, this can be simplified to:

task printFlavorName << {
    android.applicationVariants.all {
        println flavorName
    }
}

OTHER TIPS

Will like to add on to dcow answer.

After getting the flavor, to get the BuildConfig field :

variant.productFlavors.each { flavor ->
    flavor.buildConfigFields.each { key, value ->
        if(key == "APP_FLAVOR_NAME") {
            println value.type
            println value.name
            println value.value
        }    
    }
}

BuildConfigs are defined as a final class. Fields are private. So only read-only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top