buildConfigField depending on flavor + buildType

I’m trying to define a buildConfigVariable depending on the flavor + buildType. Ideally, this is what I want

productFlavors {
    strawberry {
        buildConfigField "String", "WS_API_KEY", name + variant.buildType.name
    }
    ... more flavors ..
}

name does contain “strawberry”, but I don’t know if it’s possible to access the variant‘s buildType.

  • How to check the Internet Connection periodically in whole application?
  • react-native-tcp not working on Android 7+
  • Dagger 2 - two provides method that provide same interface
  • Hiding items in listview properly
  • Widget disappearing every time the app is updated on Samsung devices
  • Android equivalent to CocoaPods Pods-Acknowledgements.plist?
  • Placed outside the Android closure I do have access to the BuildType and variant, but then I can’t invoke buildConfigField

    android.applicationVariants.all { variant ->
        println "****************************"
        println "variant: ${variant.name}"
        println "flavor: ${variant.flavorName}"
        println "****************************"
    
        if (variant.buildType.name == 'release') {
            if (variant.flavorName == 'strawberry') {
                buildConfigField "String", "WS_API_KEY", '"strawberry_release"'
            } else {
                buildConfigField "String", "WS_API_KEY", '"chocolate_release"'
            }
        } else if(variant.buildType.name == 'debug') {
            if (variant.flavorName == 'strawberry') {
                buildConfigField "String", "WS_API_KEY", '"strawberry_debug"'
            } else {
                buildConfigField "String", "WS_API_KEY", '"chocolate_debug"'
            }
        }
    
    
    ****************************
    variant: strawberryRelease
    flavor: strawberry
    ****************************
    org.gradle.api.internal.MissingMethodException: 
        Could not find method buildConfigField() 
        for arguments [String, WS_API_KEY, "strawberry_release"]
    

    I can easily create a Java factory and return the appropriate API_KEY depending on some BuildConfig constants, but I’d rather keep the code configuration agnostic.

    Related posts:

    5.1 Crash - A TaskDescription's primary color should be opaque
    How to create a drop down view like Google Calendar using Toolbar?
    Add Google Analytics Library to a Maven Project
    how to getPackageManager in fragment Android
    java.io.FileNotFoundException: (No such file or directory)
    Android Studio and Gradle dependency integration
  • How can I debug this NullPointer Exception?
  • android what is wrong with openFileOutput?
  • How to split Linear Layout in to two columns?
  • In android how to make a image grow from one point using animation?
  • Scroll ListView smoothly and programmatically
  • Attribute “empty” not working as expected with SimpleFramework
  • 2 Solutions collect form web for “buildConfigField depending on flavor + buildType”

    Edit2: The version after 0.14.2 will allow doing this:

    applicationVariants.all { variant ->
        variant.buildConfigField "int", "VALUE", "1"
    }
    

    So you’d be able to do something like this (to match the original question):

    applicationVariants.all { variant ->
        variant.buildConfigField "String", "WS_API_KEY", variant.productFlavors.get(0).name + '_' + variant.buildType.name
    }
    

    Edit: it’s not currently possible. The API is missing for this.
    Bug: https://code.google.com/p/android/issues/detail?id=67416

    Try this:

    applicationVariants.all { variant ->
        variant.mergedFlavor.buildConfigField "String", "NAME", '"VALUE"'
    }
    

    Warning: this might be a fragile solution, use at your own risk. See https://code.google.com/p/android/issues/detail?id=67416

    This is how I accomplished what I wanted. You need to change the values just before the task is executed, so I needed a way to hook my code in there.

    final projectName = project.name
    gradle.taskGraph.beforeTask { Task task ->
        if (task.path ==~ /:$projectName:generate.*BuildConfig/) {
            //extracts flavor and buildType name. See http://stackoverflow.com/a/7594052/218473 for regex
            final values = task.name.replace("generate","").replace("BuildConfig","").split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")
    
            final flavorName = values[0].toLowerCase()
            final buildTypeName = values[1].toLowerCase()
    
            com.android.build.gradle.api.ApplicationVariant variant;
            android.applicationVariants.all { currentVariant ->
                if (currentVariant.getVariantData().getVariantConfiguration().getBuildType().getName() == buildTypeName) {
                    if (currentVariant.getVariantData().getVariantConfiguration().getFlavorName() == flavorName) {
                        variant = currentVariant;
                    }
                }
            }
    
            if(variant != null) {
                com.android.builder.internal.ClassFieldImpl apiKeyField
                if (flavorName == 'strawberry') {    
                    if (buildTypeName == 'release') {
                        apiKeyField = new com.android.builder.internal.ClassFieldImpl("String", "WS_API_KEY", '"strawberry_release"')
                    } else {
                        apiKeyField = new com.android.builder.internal.ClassFieldImpl("String", "WS_API_KEY", '"strawberry_debug"')
                    }
                } else if (flavorName == 'chocolate') {                        
                    if (buildTypeName == 'release') {
                        apiKeyField = new com.android.builder.internal.ClassFieldImpl("String", "WS_API_KEY", '"chocolate_release"')
                    } else {
                        apiKeyField = new com.android.builder.internal.ClassFieldImpl("String", "WS_API_KEY", '"chocolate_debug"')
                    }
                }
    
                variant.getVariantData().getVariantConfiguration().getFlavorConfigs().get(0).addBuildConfigField(apiKeyField)
            }
        }
    }
    

    To understand why this works, download the AOSP source code and check VariantConfiguration.getBuildConfigItems()

    Using Xavier’s answer throws a MethodMissingError. If I use variant.mergedFlavor.addBuildConfigField() there’s no error, but the variable isn’t added.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.