Automatic per-variant google_services.json configurations with Gradle

Zak Taccardi
Google Cloud - Community
2 min readAug 26, 2015

You can use https://developers.google.com/mobile/add to easily generate a google_services.json file that your app can use to specify API variables for things like AppEngine, Analytics, GCM, etc. Follow the documentation at the Google Developers site to set it up.

After setup, it works well — but what if you want to use to use different API keys in your debug vs. release buildTypes? Unfortunately, the google_services.json must reside in the root of your :app module and not within a buildType/productVariant folder, so Gradle cannot handle this automatically for you via folder placement. Never fear — with some custom Gradle tasks we can fix this!

First, place the respective google_services.json for each buildType in the following locations:

app/src/debug/google_services.json
app/src/main/google_services.json

Now, let’s whip up some gradle tasks in your :app’s build.gradle to automate moving the appropriate google_services.json to app/google_services.json

task switchToDebug(type: Copy) {
description = 'Switches to DEBUG google-services.json'
from "src/debug"
include "google-services.json"
into "."
}

task switchToRelease(type: Copy) {
description = 'Switches to RELEASE google-services.json'
from "src/release"
include "google-services.json"
into "."
}

Great — but having to manually run these tasks before you build your app is cumbersome. We would want the appropriate copy task above run sometime before :assembleDebug or :assembleRelease is run. Let’s see what happens when :assembleRelease is run:

Zaks-MBP:my_awesome_application zak$ ./gradlew assembleRelease
Parallel execution is an incubating feature.
.... (other tasks)
:app:processReleaseGoogleServices
....
:app:assembleRelease

Notice the :app:processReleaseGoogleServices task. This task is responsible for processing the root google_services.json file. We want the correct google_services.json to be processed, so we must run our copy task immediately beforehand.

Add this to your build.gradle. Note the afterEvaluate enclosing.

afterEvaluate {
processDebugGoogleServices.dependsOn switchToDebug
processReleaseGoogleServices.dependsOn switchToRelease
}

Now, anytime :app:processReleaseGoogleServices is called, our newly defined :app:switchToRelease will be called beforehand. Same logic for the debug buildType. You can run :app:assembleRelease and the release version google_services.json will be automatically copied to your app module’s root folder.

Voila! Remember you can hook into any Gradle task for preprocessing via Gradle’s dependency management system.

You can see the code on its own in this gist. Feel free to offer any improvements to this process!

--

--