Android using Gradle Build flavors in the code like an if case

I'm trying to work with build flavors. In my build.gradle I've defined 2 flavors, a normal flavor and an admin flavor.

Basicly, the admin flavor has an extra button on the main activity.

I understand that I can define different packages/classes for different flavors. But is there a way to make a sort of if case to add/remove a piece of code depending on the flavor?

Basicly, I would need two versions of an Activity. But I don't want two entire different versions of the activity and maintain them.

So in my activity I would like to do

=> gradle check if flavor is 'admin'

=> if yes, add this code of the button

Is this possible? Or would you need two different physical activities and thus maintain both of them when you add functionality afterwards.


Solution 1:

BuildConfig.FLAVOR gives you combined product flavor. So if you have only one flavor dimension:

productFlavors {
    normal {
    }

    admin {
    }
}

Then you can just check it:

if (BuildConfig.FLAVOR.equals("admin")) {
    ...
}

But if you have multiple flavor dimensions:

flavorDimensions "access", "color"

productFlavors {
    normal {
        dimension "access"
    }

    admin {
        dimension "access"
    }

    red {
        dimension "color"
    }

    blue {
        dimension "color"
    }
}

there are also BuildConfig.FLAVOR_access and BuildConfig.FLAVOR_color fields so you should check it like this:

if (BuildConfig.FLAVOR_access.equals("admin")) {
    ...
}

And BuildConfig.FLAVOR contains full flavor name. For example, adminBlue.

Solution 2:

To avoid plain string in the condition, you can define a boolean property:

productFlavors {
    normal {
        flavorDimension "access"
        buildConfigField 'boolean', 'IS_ADMIN', 'false'
    }

    admin {
        flavorDimension "access"
        buildConfigField 'boolean', 'IS_ADMIN', 'true'
    }
}

Then you can use it like this:

if (BuildConfig.IS_ADMIN) {
    ...
}