Figuring out how to pull the current flavor from gradle
While working on an update for one of our games, I needed to figure out how to get the current flavor and use it in code. Since there are a lot of ways to do this, I chose to create a custom build config parameter and set the value in each variant I have.
Adding a new build config field
First thing is to add a new build config property in your flavors. Using buildConfigField helps us do that. Therefore I defined a String called VARIANT and set the value to paid or free depending on what flavors I have.
productFlavors { paid { ... buildConfigField "String", "VARIANT", "\"paid\"" } free { ... buildConfigField "String", "VARIANT", "\"free\"" } }
Just in case you don’t know where productFlavors should be put, it is inside the android definition of your build.gradle.
By doing this you can access that value in your code using the BuildConfig class that is generated by Gradle. You can use the same class to check if the current build is in debug/release mode or other stuff.
Get the current flavor name
Now, to access the newly created property and use it I do something like this:
if (BuildConfig.FLAVOR.equals("paid")){ // do what you need to do for the paid version } else { // do what you need to do for the free version }
Conclusions
I use this approach because it gives me the power to name the flavors to whatever I want. I also feel that is less hacky than looping through different directories or figuring out paths to get the flavor and in the end if the flavor name gets changed maybe I will forget to change it in the code as well..
Probably there are a lot more ways to get to the same thing but this feels to me that is a viable solution :). I am curious to see other ways to do the same thing from others. Please post your own solution in the comments below. Thanks!