androidgradleandroid-flavors

How to keep a Java file for two flavors and exclude it for others in my app?


I have an Android app with, say, three flavors. The first one is called free. The second flavor is called paid. And the third flavor is called b2bClient.

free and pro need a library (let it be Google Analytics), and, in order to avoid code duplication, the helper class GoogleAnalyticsHelper surrounding calls to Google Analytics is in the main source set. But b2bClient doesn't use the library. To reduce the size of the b2bClient APK, I don't include the library to its dependencies in Gradle. It causes a compilation error when I run assembleB2bClient which is obvious (the build system just doesn't have classes from com.google.android.gms.analytics.

I tried excluding GoogleAnalyticsHelper from the source set when the flavor is b2bClient like this:

sourceSets {

    main {
        android.productFlavors.all { flavor ->
            if (flavor.name == "b2bClient") {
                java.exclude("**/GoogleAnalyticsHelper.java")
            }
        }
    }

}

That didn't work, either. The same error. Is it possible to exclude a class from the main source set for a specific flavor?


Solution

  • Create a library module say analytics which contains the code of GoogleAnalyticsHelper. Now add this analytics library only for flavor requires analytics behavior.

    Follow this link to include a library for a specific flavor only.