buildConfigField depending on flavor + buildType

前端 未结 2 543
离开以前
离开以前 2020-12-05 08:19

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

productFlavors {
            


        
2条回答
  •  隐瞒了意图╮
    2020-12-05 08:46

    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("(?
                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.

提交回复
热议问题