Monday, November 11, 2019

Android Studio: Automatically replace the Google Maps V2 API Key for debug and release mode

The Android Google Maps API requires a separate debug and release keys in the Android Studio project's AndroidManifest.xml file, as shown in the listing below.

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_google_maps_v2_api_debug_or_release_key_here" />
It can get tedious having to replace the key every time you want to debug or to generate a release build APK.

It is possible to use Gradle to automate the replacement of the Google Maps V2 API key value by using constants defined in the Gradle build types. To automate the replacement, you can do the following:
  1. In the Android app's build.gradle file, add in the following line under the debug component of buildTypes:

    resValue "string", "google_maps_v2_api_key", "your_google_maps_v2_debug_api_key_here"

    Note: replace the api key accordingly; and the constant name is google_maps_v2_api_key.
  2. Similarly, add in the following line under the release component of buildTypes:

    resValue "string", "google_maps_v2_api_key", "your_google_maps_v2_release_api_key_here"
  3. The Android app's build.gradle should look like this screenshot below:


  4. Now, in the app's AndroidManifest.xml file, replace the Google Maps V2 API key metadata value to the string constant name google_maps_v2_api_key.

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

Now you can debug or build the Android app as per normal without manually replacing the Google Maps V2 API key.

No comments: