Stephan Celis Stephan Celis - 3 months ago 16
Android Question

Android using 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 flavours. 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 flavour 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.

Answer

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 {
        flavorDimension "access"
    }

    admin {
        flavorDimension "access"
    }

    red {
        flavorDimension "color"
    }

    blue {
        flavorDimension "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.