Dynamically generate package name for multi-flavors configuration
Asked Answered
E

1

2

I have Gradle Android project that will be used for several customers. Also it will have free and paid version. I realized that it can be achieved by using flavorDimensions. But the problem is that I want to have a method to generate package name depending on selected flavors.

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'
    }
}

I wonder when do I need to call this method and what variable do I need to set?

Exorcist answered 19/6, 2014 at 9:43 Comment(0)
E
5

Figured it out how to implement this. Groovy code below allows to get flexibility in generation of package names.

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)
    }

    // ...

}
Exorcist answered 20/6, 2014 at 14:1 Comment(1)
Note: This has been changed slightly. Instead of 'variant.mergedFlavor.packageName' you now need 'variant.mergedFlavor.applicationId'Abagael

© 2022 - 2024 — McMap. All rights reserved.