Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

android - How to set different applicationId for each flavor combination using flavorDimensions when using Gradle Kotlin-DSL?

I am converting an Android app to the Gradle Kotlin-DSL by using Kotlinscript files.

I have a problem converting our applicationId logic. We don't use the defaultConfiguration with applicationId plus various applicationIdSuffix for our flavors but a custom logic. The logic is described in this SO answer, here is the groovy code:

flavorDimensions "price", "dataset"

productFlavors {
    free { dimension "price" }
    paid { dimension "price" }
    dataset1 { dimension "dataset" }
    dataset2 { dimension "dataset" }
}

android.applicationVariants.all { variant ->
    def mergedFlavor = variant.mergedFlavor
    switch (variant.flavorName) {
        case "freeDataset1":
            mergedFlavor.setApplicationId("com.beansys.freeappdataset1")
            break
        case "freeDataset2":
            mergedFlavor.setApplicationId("com.beansys.freedataset2")
            break
        case "paidDataset1":
            mergedFlavor.setApplicationId("com.beansys.dataset1paid")  
            break
        case "paidDataset2":
            mergedFlavor.setApplicationId("com.beansys.mypaiddataset2")
            break
    }
}

With kotlin I cannot alter the applicationId of the mergedFlavor like in groovy. It is a val and therefore can't be changed.

Any elegant solution to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Google added the variants API with the Android Gradle Plugin 7.0.0. With it we can alter the applicationId.

android {
    flavorDimensions.addAll(listOf("price", "dataset"))

    productFlavors {
        create("free") { dimension = "price" }
        create("pro") { dimension = "price" }
        create("dataset1") { dimension = "dataset" }
        create("dataset2") { dimension = "dataset" }
    }
}

androidComponents {
    onVariants { variant ->
        val applicationId = when(variant.flavorName) {
            "freeDataset1" -> "com.beansys.freeappdataset1"
            "freeDataset2" -> "com.beansys.freedataset2"
            "proDataset1" -> "com.beansys.dataset1paid"
            "proDataset2" -> "com.beansys.mypaiddataset2"
            else -> throw(IllegalStateException("Whats your flavor? ${variant.flavorName}!"))
        }
        variant.applicationId.set(applicationId)
    }
}

Note that it is probably better to use a task to determine the applicationId.

For more informations see the following resources:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...