动态生成多种配置的包名称

时间:2014-06-19 09:43:04

标签: android gradle android-build package-name

我有Gradle Android项目,将用于多个客户。它还有免费和付费版本。我意识到可以通过使用flavorDimensions来实现。但问题是我希望有一种方法来根据所选的口味生成包名。

flavorDimensions 'branding', 'version'
productFlavors {
    free {
        flavorDimension 'version'
    }
    paid{
        flavorDimension 'version'
    }
    customer1 {
        flavorDimension 'branding'
    }
    customer2 {
        flavorDimension 'branding'
    }
}

// pseudocode
def getGeneratePackageName() {
    if (customer1 && free) {
        return 'com.customer1.free'
    }
    if (customer2 && free) {
        return 'com.customer2.free'
    }
    if (customer1 && paid) {
        return 'com.customer1.paid'
    }
    if (customer2 && paid) {
        return 'com.customer2.paid'
    }
}

我想知道何时需要调用此方法以及需要设置哪个变量?

1 个答案:

答案 0 :(得分:3)

想出如何实现这一点。下面的Groovy代码允许灵活地生成包名称。

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.packageName = 'com.customer1.variant1'
        } else if (projectFlavorNames.contains('customer2') && projectFlavorNames.contains('variant2')) {
            variant.mergedFlavor.packageName = 'com.customer2.variant2'
        } // else use standard package name

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

    // ...

}