Share Android.variantFilter for all app modules

741 views Asked by At

I would like to use the same implementation for the android.variantFilter(...) for all my android apps modules.

Currently I have such a variantFilter in the "app"-Module which works fine:

android.variantFilter { variant ->
    String buildType = variant.buildType.name
    String flavor = variant.getFlavors().get(0).name

    if ((buildType == 'debug' && (flavor == 'canary' || flavor == 'int' || flavor == 'prd')) ||
            (buildType == 'release' && (flavor == 'dev' || flavor == 'loc')))
        variant.setIgnore(true)
}

The app contains several modules however and I would like to filter the variants in all modules likewise. Without having to reimplement the same variantFilter in all module's build.gradle files.

So my question is: is there a way to define that filter in a central place (for example the app's top level builg.gradle file) and to cite it in the module specific build.gradle files?

2

There are 2 answers

3
Martin Zeitler On BEST ANSWER

Either put the script in a file called variants.gradle in the parent directory and apply it:

apply from: '../variants.gradle'

Or use AndroidComponentsExtension.beforeVariants

At this stage, access to the DSL objects is disallowed, use finalizeDsl method to programmatically access the DSL objects before the VariantBuilderT object is built.

and DslLifecycle.finalizeDsl (the only option available):

API to customize the DSL Objects programmatically after they have been evaluated from the build files and before used in the build process next steps like variant or tasks creation.

Which means, that variants can be programmatically configured, without declaring them explicitly. See this answer of mine... it's possibly not variant.setIgnore(true) but variant.enabled = false.

1
djmonki On

I believe this is what you want to achieve at the top level build.gradle or is this what you already have:

android {
    ...
    defaultConfig {...}
    buildTypes {
        debug{...}
        release{...}
    }
    productFlavors {
        canary {...}
        int {...}
        prd {...}
        dev {...}
        loc {...}
    }
    variantFilter { variant ->
        String buildType = variant.buildType.name
        String flavor = variant.flavors*.name
        
        if ((buildType == 'debug' && (flavor == 'canary' || flavor == 'int' || flavor == 'prd')) ||
                (buildType == 'release' && (flavor == 'dev' || flavor == 'loc')))
            variant.setIgnore(true)
    }
}

There is more info on the official developer.android webpage: Configure Build Variants