Search code examples
androidgradlebuild.gradledynamic-feature-module

Restrict dynamic feature module to certain BuiltTypes


I have an app with two flavors and 6 buildTypes. I'm developing a dynamic feature module, but I don't want it included in the release bundle. Is there a way to do this using buildTypes? I've tried adding the dynamicFeatures = ["mymodule"] within the desired buildTypes, but it still gets added to the release bundle. I know I can specify it as on-demand in the module's manifest to prevent it from being added to apks installed by users, but I'd prefer to keep it out of the release bundle all together. Is there a way to do this?


Solution

  • Here's what I did:

    I created another gradle file called dynamic_features.gradle. This is what it looks like:

    if (hasProperty('is_release_build')) {
        android {
            buildTypes {
                debug {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'false'
                }
                qa {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'false'
                }
                release {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'false'
                }
                staging {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'false'
                }
                debugDaily {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'false'
                }
                local {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'false'
                }
            }
        }
    } else {
        android {
            buildTypes {
                debug {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'true'
                }
                qa {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'true'
                }
                release {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'true'
                }
                staging {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'true'
                }
                debugDaily {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'true'
                }
                local {
                    buildConfigField 'boolean', 'HAS_DYNAMIC_FEATURES', 'true'
                }
            }
    
            dynamicFeatures = [":<features>"]
        }
    }
    

    Then, I added -Pis_release_build to my build script: ./gradlew clean bundleAppRelease -Pis_release_build.

    Finally, I added apply from: 'dynamic_features.gradle' to my app level build.gradle. Bundles generated with the build script don't include the feature module. The buildConfigField is optional, but useful if you want to check whether or not that feature is available at runtime.