如需将应用配置为使用 Places SDK for Android,请按以下步骤操作。所有使用 Places SDK for Android 的应用都必须设置这些变量。
第 1 步:设置 Android Studio
- 必须使用 Android Studio Arctic Fox 或更高版本。如果您尚未安装,请下载并安装。
- 确保您在 Android Studio 中使用的是 Android Gradle 插件 7.0 或更高版本。
第 2 步:设置 SDK
Places SDK for Android 库可通过 Google 的 Maven 制品库获得。要将 SDK 添加到您的应用中,请执行以下操作:
- 在顶级
settings.gradle
文件的pluginManagement
代码块下,添加 Gradle 插件门户、Google 的 Maven 制品库和 Maven 中央制品库。pluginManagement
代码块必须位于脚本中的任何其他语句之前。pluginManagement { repositories { gradlePluginPortal() google() mavenCentral() } }
- 在顶级
settings.gradle
文件的dependencyResolutionManagement
代码块下,添加 Google 的 Maven 制品库和 Maven 中央制品库:dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } }
-
在模块级
build.gradle
文件的dependencies
部分中,向 Places SDK for Android 添加一个依赖项:dependencies { implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version")) implementation 'com.google.android.libraries.places:places:3.3.0' }
- 在模块级
build.gradle
文件中,将compileSdk
和minSdk
设置为以下值:android { compileSdk 31 defaultConfig { minSdk 21 // ... }
第 3 步:将您的 API 密钥添加到项目中
本部分介绍了如何存储 API 密钥,以便您的应用可以安全引用该密钥。您不应将 API 密钥签入版本控制系统,因此我们建议将其存储在项目根目录下的 secrets.properties
文件中。如需详细了解 secrets.properties
文件,请参阅 Gradle 属性文件。
为了简化此任务,建议您使用 Android 版 Secret Gradle 插件。
如需在 Google 地图项目中安装 Android 版 Secret Gradle 插件,请执行以下操作:
-
在 Android Studio 中,打开项目级
build.gradle
文件,并将以下代码添加到buildscript
下的dependencies
元素中。Groovy
buildscript { dependencies { classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1" } }
Kotlin
buildscript { dependencies { classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1") } }
-
Open your module-level
build.gradle
file and add the following code to theplugins
element.Groovy
plugins { // ... id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' }
Kotlin
plugins { id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") }
- Save the file and sync your project with Gradle.
-
Open the
secrets.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