Gradle:android.variantFilter 导致升级到 Gradle 2.2.1 后构建失败

Gradle: android.variantFilter cause build fail after upgrade to Gradle 2.2.1

我在一个有很多风格的 Android 项目中工作,我在 build.gradle 中使用这段代码为每个风格设置包名称:

flavorDimensions "type", "feature"

productFlavors {
    abc { flavorDimension "type" }

    def { flavorDimension "type" }

    ABC { flavorDimension "feature" } 

    DEF { flavorDimension "feature" } 
}
android.variantFilter { variant ->
    def flavorString = ""
    def flavors = variant.getFlavors()
    for (int i = 0; i < flavors.size(); i++) {
        flavorString += flavors[i].name;
    }
    if(flavorString.equalsIgnoreCase("abcABC")) {
        variant.getDefaultConfig().applicationId "com.my.app.abc.abc"
    }
    if(flavorString.equalsIgnoreCase("abcDEF")) {
        variant.getDefaultConfig().applicationId "com.my.app.abc.def"
    }
    if(flavorString.equalsIgnoreCase("defABC")) {
        variant.getDefaultConfig().applicationId "com.my.app.def.abc"
    }
    if(flavorString.equalsIgnoreCase("defDEF")) {
        variant.getDefaultConfig().applicationId "com.my.app.def.def"
    }
}

一切都很好,直到我将 gradle 从 1.10.0 更新到 2.2.1,构建失败并且我收到此错误消息:

Error:(63, 0) No signature of method: com.android.build.gradle.internal.api.ReadOnlyProductFlavor.applicationId() is applicable for argument types: (java.lang.String) values: [com.hac.apps.megahd.acc]
Possible solutions: getApplicationId()

看来 variant.getDefaultConfig().applicationId 现在的工作方式有所不同。我在互联网上搜索了 android.variantFilter 的文档,但它似乎不存在。

任何人都可以告诉我如何让这段代码在 gradle 2.2.1 中工作?非常感谢。

variantFilter 仅用于允许或禁止构建某些组合。 defaultConfig 对象是共享的和只读的。如果您想将 applicationId 分配给变体,我认为您应该更类似于此:

buildTypes {
applicationVariants.all { variant ->

    def projectFlavorNames = []

    variant.productFlavors.each() { flavor ->
        projectFlavorNames.add(flavor.name)
    }

    project.logger.debug('Application variant ' + variant.name + '. Flavor names list: ' + projectFlavorNames)

    if (projectFlavorNames.contains('customer1') && projectFlavorNames.contains('variant1')) {
        variant.mergedFlavor.applicationId = 'com.customer1.variant1'
    } else if (projectFlavorNames.contains('customer2') && projectFlavorNames.contains('variant2')) {
        variant.mergedFlavor.applicationId = 'com.customer2.variant2'
    } // else use standard package name

    project.logger.debug('Using project name: ' + variant.packageName)
}

// ...

}

来自Dynamically generate package name for multi-flavors configuration