Adding flavor-specific tasks to Gradle

Suppose you have a multi-flavored project. Each flavor is a separate app, so you have to use separate google-services.json file for each flavor.

The problem is that google-services.json file must be placed in the app/ directory (update: as of version 2.0.0-alpha3 of the plugin support was added for build types), so we have to copy this file to app/ directory on every flavor build process.

If we want to automate this process, we can add flavor-specific tasks to our build.gradle file and make them run depending on what flavor we are building.

Here is my way of achieving this.

First of all, Add this code to productFlavors section:

This will create tasks flavor1GoogleServices, flavor2GoogleServices and so on. This task will copy google-services.json file from src/flavor1/ folder to app/ folder.

Now add this code to the end of the build.gradle file:

This code runs after a project is evaluated. It adds dependencies to tasks generateFlavor1DebugResources, generateFlavor2DebugResources etc. on our tasks.

That’s all. After switching build variant in Android Studio the right task for this variant will run and update json-file.

Written by

Head of Applications @ Mews

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store