Initial Setup

I know I named this post “Advanced Android Flavors” but we’ll start with basics. I’ll cover the more advanced topics in the upcoming posts.

The flavor mechanism allows us to create build variants easily. The most common case would be creating a demo and full or a free and paid version of an app. In my case, flavors allow me to support our clients.

Let’s configure our first flavors for our two clients, named client1 and client2. In our module’s build.gradle file inside the android section, we’ll add our first two flavors. To keep things separate, we’ll add a suffix to the application ID for each:

android {



//...



productFlavors {

client1 {

applicationIdSuffix ".client1"

}

client2 {

applicationIdSuffix ".client2"

}

}

Let’s Gradle sync and check out our new build variants. Open the Build Variants tab in Android Studio. It’s usually on the left panel of the screen by default. If you can’t find it use the menus: View > Tool Windows > Build Variants.

The build variant dropdown for our app module now contains client1 and client2. Each has its own build type variation. More on that in a later post.

Adding Flavor-Specific Code

Now let’s take a look at the project folder structure. It probably looks something like this:

YourAndroidProject/

app/

src/

main/

We can now create identically named classes / resources / libraries with flavor-specific implementations. This way, we can change our logic according to the configuration.

Shared code goes into the main folder. To add flavor-specific code, add files into a folder with the same name as your flavor. The flavor folders must be structured the same way the main folder is.

If, for example, we’d like to have client specific strings, it could look something like this:

YourAndroidProject/

app/

src/

main/

<contents of main>

client1/

res/

values/

client_strings.xml

client2/

res/

values/

client_strings.xml

Switching between build variants will include only one of the client_strings. Kind of cool, right?

This is quite a simple scenario. It doesn’t cover the code sharing and server picking aspects I mentioned in the beginning of this post. In the next post, we’ll dive deeper and handle these cases.

Up next: Enter Flavor Dimensions