如需将应用配置为使用 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 'com.google.android.libraries.places:places:3.1.0' }
- 在模块级
build.gradle
文件中,将compileSdk
和minSdk
设置为以下值:android { compileSdk 31 defaultConfig { minSdk 21 // ... }
第 3 步:将您的 API 密钥添加到项目中
本部分介绍了如何存储 API 密钥,以便您的应用可以安全引用该密钥。您不应将 API 密钥签入版本控制系统,因此我们建议将其存储在项目根目录下的 local.properties
文件中。如需详细了解 local.properties
文件,请参阅 Gradle 属性文件。
为了简化此任务,我们建议您使用 Android 版 Secrets Gradle 插件。如需安装此插件并存储您的 API 密钥,请执行以下操作:
- 在 Android Studio 中,打开项目级
build.gradle
文件,并将以下代码添加到buildscript
下的dependencies
元素中。plugins { // ... id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' version '2.0.1' apply false }
- 接下来,打开模块级
build.gradle
文件,并将以下代码添加到plugins
元素中。id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
- 保存文件并将项目与 Gradle 同步。
- 在项目级目录中打开
local.properties
,然后添加以下代码。将YOUR_API_KEY
替换为您的 API 密钥。MAPS_API_KEY=YOUR_API_KEY
- 保存文件。
- 在
AndroidManifest.xml
文件中,转到com.google.android.geo.API_KEY
并按如下所示更新android:value attribute
:<meta-data android:name="com.google.android.geo.API_KEY" android:value="${MAPS_API_KEY}" />
注意:如上所示,建议使用 com.google.android.geo.API_KEY
作为 API 密钥的元数据名称。可使用具有该名称的密钥向 Android 平台上的多个基于 Google 地图的 API(包括 Places SDK for Android)进行身份验证。为了实现向后兼容性,该 API 还支持使用 com.google.android.maps.v2.API_KEY
作为名称。使用这个旧名称时只能接受 Android Maps API v2 的身份验证。应用只能指定其中一个 API 密钥元数据名称。如果两个都指定,API 会抛出异常。
第 4 步:初始化 Places API 客户端
在 activity 或 fragment 中初始化 Places SDK for Android,如以下示例所示:请注意,调用 Places.initialize()
时需传递 API 密钥:
Java
// Initialize the SDK Places.initialize(getApplicationContext(), apiKey); // Create a new PlacesClient instance PlacesClient placesClient = Places.createClient(this);
Kotlin
// Initialize the SDK Places.initialize(applicationContext, apiKey) // Create a new PlacesClient instance val placesClient = Places.createClient(this)
现在,您可以开始使用 Places SDK for Android 了!
第 5 步:设置 Android 设备
如需运行使用 Places SDK for Android 的应用,您必须将其部署到搭载 Android 4.0 或更高版本且包含 Google API 的 Android 设备或 Android 模拟器。
- 如要使用 Android 设备,请按照在硬件设备上运行应用中的说明进行操作。
- 如要使用 Android 模拟器,您可以使用 Android Studio 附带的 Android 虚拟设备 (AVD) 管理器创建虚拟设备并安装模拟器。