Manage Google Maps API Key with Gradle in Android Studio

I know Gradle is powerful and I would like to manage the API keys for development/produciton of Google Maps

Currently I always need to manually comment one line and uncomment the other to make it work. Is there a way to do it automatically in Gradle with some custom release configuration ?

<!-- MapView v2 API -->
<uses-library android:name="com.google.android.maps" />
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="[MY_DEV_KEY]" />
<!-- PROD
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="[MY_PROD_KEY]" />
-->

Solution 1:

Since you are using gradle you can do the following:

build.gradle

android {
  .. .. ...
    buildTypes {
       debug {
          resValue "string", "google_maps_api_key", "[YOUR DEV KEY]"
       }
       release {
           resValue "string", "google_maps_api_key", "[YOUR PROD KEY]"
       }
    }
  }

And in your AndroidManifest.xml

<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_api_key"/>

This way you only have one AndroidManifest.xml and you set value based on your build type. Hope this helps.

Solution 2:

You can achieve this with manifest placeholder feature: http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger#TOC-Placeholder-support

in build.gradle file:

buildTypes {
    debug {
        manifestPlaceholders = [ google_map_key:"your_dev_key"]
    }
    release {
        manifestPlaceholders = [ google_map_key:"prod_key"]
    }
}

and then in manifest:

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="${google_map_key}"/>

That's exact thing for different keys for different flavors and this is cleaner solution than using string resources.

P.S. On the other hand I would better consider getting api keys from backend and do not hardcode them on the client. This is more secure and more flexible approach.