Multi flavor app based on multi flavor library in Android Gradle

Finally I found out how to do this, I will explain it here for others facing same problem:

If App and Library have same Flavor name(s)

It’s possible since Gradle Plugin 3.0.0 (and later) to do something like:

Library build.gradle:

apply plugin: 'com.android.library'

// Change below's relative-path
// (as the `../` part is based on my project structure,
// and may not work for your project).
apply from: '../my-flavors.gradle'

dependencies {
    // ...
}

android {
    // ...
}

Project build.gradle:

buildscript {
    // ...
}

apply plugin: 'com.android.application'
// Note that below can be put after `dependencies`
// (I just like to have all apply beside each other).
apply from: './my-flavors.gradle'

dependencies {
    api project(':lib')
}

android {
    productFlavors {
        // Optionally, configure each flavor.
        market1 {
            applicationIdSuffix '.my-market1-id'
        }
        market2 {
            applicationIdSuffix '.my-market2-id'
        }
    }
}

My flavors .gradle:

android {
    flavorDimensions 'my-dimension'
    productFlavors {
        market1 {
            dimension 'my-dimension'
        }
        market2 {
            dimension 'my-dimension'
        }
    }
}

If App or Library has different Flavor-name (old answer)

The key part is to set publishNonDefault to true in library build.gradle, Then you must define dependencies as suggested by user guide.

Update 2022; publishNonDefault is now by default true, and setting it to false is ignored, since said option is deprecated.

The whole project would be like this:

Library build.gradle:

apply plugin: 'com.android.library'

android {        
    ....
    publishNonDefault true
    productFlavors {
        market1 {}
        market2 {}
        market3 {}
    }
}

project build.gradle:

apply plugin: 'com.android.application'

android {
    ....
    productFlavors {
        market1 {}
        market2 {}
        market3 {}
    }
}

dependencies {
    ....
    market1Compile project(path: ':lib', configuration: 'market1Release')
    market2Compile project(path: ':lib', configuration: 'market2Release')

    // Or with debug-build type support.
    android.buildTypes.each { type ->
        market3Compile project(path: ':lib', configuration: "market3${type.name}")
    }

}

Now you can select the app flavor and Build Variants panel and the library will be selected accordingly and all build and run will be done based on the selected flavor.

If you have multiple app module based on the library Android Studio will complain about Variant selection conflict, It’s ok, just ignore it.

enter image description here

Leave a Comment