Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 523
Stephan Celis Avatar asked Jun 09 '14 11:06

Stephan Celis


People also ask

What is BuildConfig flavor?

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.

How do I get the current flavor in Gradle?

There is no direct way to get the current flavor; the call getGradle(). getStartParameter().


2 Answers

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.

like image 87
mixel Avatar answered Nov 13 '22 22:11

mixel


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) {     ... } 
like image 33
user2878850 Avatar answered Nov 13 '22 23:11

user2878850