ProductFlavor is a very powerful feature available in the Android gradle plugin that allows us to manage different “flavors” of an application.
This is useful when you want the same application but with different features per flavor (e.g. Full Version vs Free Version).
In this post we will build a simple weather app that will display the current temperature for a given city using openweathermap.org. To illustrate our point, this fully integrated app will be called the “Full” version.
We will add a different flavor called “Demo” version for our marketing team so users can use the app without the real data. The “Full” version app will make web service calls where as the “Demo” version app will return canned data so no web service calls are made.
Product flavor is configured in build.grade file.
In the above block, we defined “demo” and “full” product flavors. We set applicationId and app_name string resource in each flavor. Doing this allows us to install both applications at the same time on a device since they have unique applicationIds.
We also gave them different names, defined by app_name. The Full version will be named “Full App” and the Demo version will be named “Demo App”.
(Note: app_name is used in AndroidManifest.xml the application name)
Now, we will need to set up the source directories for each flavors so that we can have specific classes in them.
app/src/full/java and app/src/demo/java parallel to app/src/main/java
Common classes and resources should live in main/java package where as flavor specific classes and resources live in each flavor specific source folder we created above.
In this example we have “WeatherService.java” class in each product flavor. Class in full flavor makes calls to openweathermap.org.
Class in Demo flavor just returns a dummy data and does not make a network call.
You will find that both classes refer to “WeatherListener” which is defined in the main flavor.
Let’s build each flavor, In Android Studio, so you can pick a flavor by going to “BuildVariant” tab on the left. Let’s pick “demoDebug”. This picks the “demo” flavor with the “Debug” type. The combination of these two makes the “demoDebug” build variant.
Running this build variant will build our “Demo” version of the application. This application will show “75.0” for any city except for “Bermuda”.
Now, let’s build the “fullDebug” flavor where it will make the call to “openweathermap.org” to get the weather information for the city entered.
Here you can see that we built both full and demo versions of the app using same source.
Full code could be found at: https://github.com/manijshrestha/BuildVariantDemo
You can read more about product flavors on android gradle plugin site: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Product-flavors