Libraries can't set applicationId
and if you are working in a multi-module project and picking up flavors
from a separate file , none of the above answers will work. For a modularized app, you need the following steps -
Create a flavors.gradle
file in project root directory
ext.flavorConfig = { // 1
flavorDimensions "pricing"
productFlavors {
free {
dimension "pricing"
ext.myApplicationIdSuffix = '.free' // 2
}
paid {
dimension "pricing"
ext.myApplicationIdSuffix = '.paid'
}
}
productFlavors.all { flavor -> // 3
if (flavor.hasProperty('myApplicationIdSuffix') && isApplicationProject()) {
flavor.applicationIdSuffix = flavor.myApplicationIdSuffix
}
}
}
def isApplicationProject() { // 4
return project.android.class.simpleName.startsWith('BaseAppModuleExtension')
}
- In 1 we export a closure so that we can use it in our modules’ build.gradle files.
- In 2 we define a custom myApplicationIdSuffix property. We cannot simply have applicationIdSuffix as it is not possible to use it in library modules (build would fail if you did).
- In 3 we iterate over created flavors and set applicationIdSuffix if we detect that it’s an application module only.
- 4 is a way to check where this closure is being used.
All that’s left is to use this closure in our modules’ build.gradle
files. E.g. in application module this would look like this:
apply plugin: 'com.android.application'
apply from: "${rootProject.projectDir}/flavors.gradle"
android {
// other config...
with flavorConfig
}
If this isn't clear, you can check out this article for better understanding.