Google strongly recommends that you not check an API key into your
version control system. Instead, you should store it in the local.properties
file,
which is located in the root directory of your project and then use the
Secrets Gradle Plugin for Android
to read the API key.
The Secrets Gradle Plugin for Android reads secrets, including the API key, from
a properties file not checked into a version control system. The plugin then exposes those properties
as variables in the Gradle-generated BuildConfig
class and in the Android manifest file.
For a complete example of using the Secrets Gradle Plugin for Android to access an API key, see Set up an Android Studio project.
Installation and usage
To install the Secrets Gradle Plugin for Android in your Google Maps project:
- In your top-level
settings.gradle
file, include the Gradle plugin portal, Google Maven repository, and Maven central repository under thepluginManagement
block. ThepluginManagement
block must appear before any other statements in the script.pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() } }
- In Android Studio, open your project-level
build.gradle
file and add the following code to thedependencies
element underbuildscript
.plugins { // ... id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' version '2.0.1' apply false }
- Open your module-level
build.gradle
file and add the following code to theplugins
element.id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
- Save the file and sync your project with Gradle.
- Open the
local.properties
in your project level directory, and then add the following code. ReplaceYOUR_API_KEY
with your API key.MAPS_API_KEY=YOUR_API_KEY
- Save the file.
- In your
AndroidManifest.xml
file, go tocom.google.android.geo.API_KEY
and update theandroid:value attribute
as follows:<meta-data android:name="com.google.android.geo.API_KEY" android:value="${MAPS_API_KEY}" />
Optionally edit the properties of the plugin to specify a different secrets file or other properties. In Android Studio, open your project-level
build.gradle
file and edit thesecrets
property:secrets { // Optionally specify a different file name containing your secrets. // The plugin defaults to "local.properties" propertiesFileName = "secrets.properties" // A properties file containing default secret values. This file can be // checked in version control. defaultPropertiesFileName = 'local.defaults.properties' // Configure which keys should be ignored by the plugin by providing regular expressions. // "sdk.dir" is ignored by default. ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore" ignoreList.add("sdk.*") // Ignore all keys matching the regexp "sdk.*" }
What's next
- View the Secrets Gradle Plugin for Android GitHub project page.
- View Set up an Android Studio project for a complete example of using the plugin.