设置 Android Studio 项目

如需将应用配置为使用 Places SDK for Android,请按以下步骤操作。所有使用 Places SDK for Android 的应用都必须使用这些 API。

第 1 步:设置 Android Studio

本文档介绍的是使用 Android Studio HedgehogAndroid Gradle 插件 8.2 版的开发环境。

第 2 步:设置 SDK

您可以通过 Google 的 Maven 制品库获取 Places SDK for Android 库。要将 SDK 添加到您的应用中,请执行以下操作:

  1. 在顶级 settings.gradle 文件的 pluginManagement 代码块下,添加 Gradle 插件门户Google 的 Maven 制品库Maven 中央存储库pluginManagement 代码块必须位于脚本中的任何其他语句之前。
    pluginManagement {
        repositories {
            gradlePluginPortal()
            google()
            mavenCentral()
        }
    } 
  2. 在顶级 settings.gradle 文件的 dependencyResolutionManagement 代码块下,添加 Google 的 Maven 制品库Maven 中央存储库
    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            google()
            mavenCentral()
        }
    } 
  3. 模块build.gradle 文件的 dependencies 部分中,为 Places SDK for Android 添加一个依赖项:

    Groovy

    dependencies {
        // If updating kotlin-bom version number above, also edit project-level build.gradle definition of $kotlin_version variable
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version"))
        implementation 'com.google.android.libraries.places:places:3.3.0'
    }

    Kotlin

    dependencies {
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version"))
        implementation("com.google.android.libraries.places:places:3.3.0")
    }
  4. 在模块级 build.gradle 文件中,将 compileSdkminSdk 设置为以下值:

    Groovy

    android {
        compileSdk 34
    
        defaultConfig {
            minSdk 21
            // ...
        }
    }

    Kotlin

    android {
        compileSdk = 34
    
        defaultConfig {
            minSdk = 21
            // ...
        }
    }
  5. 在模块级 build.gradle 文件的 buildFeatures 部分中,添加 BuildConfig 类,用于访问稍后在此过程中定义的元数据值:

    Groovy

    android {
      // ...
      buildFeatures {
        buildConfig true
        // ...
      }
    }

    Kotlin

    android {
      // ...
      buildFeatures {
        buildConfig = true
        // ...
      }
    }

第 3 步:将您的 API 密钥添加到项目中

本部分介绍了如何存储 API 密钥,以便您的应用可以安全引用该密钥。您不应将 API 密钥签入版本控制系统,建议将其存储在项目根目录下的 secrets.properties 文件中。如需详细了解 secrets.properties 文件,请参阅 Gradle 属性文件

为了简化此任务,建议您使用 Android 版 Secret Gradle 插件

如需在 Google 地图项目中安装 Android 版 Secret Gradle 插件,请执行以下操作:

  1. 在 Android Studio 中,打开顶级 build.gradlebuild.gradle.kts 文件,并将以下代码添加到 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")
        }
    }
    
  2. 打开模块级 build.gradle 文件,并将以下代码添加到 plugins 元素中。

    Groovy

    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }

    Kotlin

    plugins {
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }
  3. 在模块级 build.gradle 文件中,请务必将 targetSdkcompileSdk 设置为 34。
  4. 保存文件并将项目与 Gradle 同步
  5. 在顶级目录中打开 secrets.properties 文件,然后添加以下代码。将 YOUR_API_KEY 替换为您的 API 密钥。secrets.properties 不会签入版本控制系统,因此请将您的密钥存储在此文件中。
    PLACES_API_KEY=YOUR_API_KEY
  6. 保存文件。
  7. 在顶级目录(即 secrets.properties 文件所在的文件夹)中创建 local.defaults.properties 文件,然后添加以下代码。

    PLACES_API_KEY=DEFAULT_API_KEY

    此文件的作用是为 API 密钥提供备用位置,以免在找不到 secrets.properties 文件的情况下构建失败。如果您是从省略 secrets.properties 的版本控制系统中克隆应用,而您还没有在本地创建 secrets.properties 文件来提供 API 密钥,就可能会出现构建失败。

  8. 保存文件。
  9. 在 Android Studio 中,打开模块级 build.gradlebuild.gradle.kts 文件,然后修改 secrets 属性。如果 secrets 属性不存在,请添加它。

    修改该插件的属性,将 propertiesFileName 设为 secrets.properties,将 defaultPropertiesFileName 设为 local.defaults.properties,然后设置任何其他属性。

    Groovy

    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.*"
    }
            

    Kotlin

    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.*"
    }
            

第 4 步:初始化 Places API 客户端

在 activity 或 fragment 中初始化 Places SDK for Android。您必须先确定要使用的 SDK 版本:Places SDK for Android 或 Places SDK for Android(新版)。如需详细了解产品版本,请参阅选择 SDK 版本

以下示例展示了如何同时为这两个版本初始化 SDK。

Places SDK for Android(新)

调用 Places.initializeWithNewPlacesApiEnabled() 时传递 API 密钥:

Kotlin

    // Define a variable to hold the Places API key.
    val apiKey = BuildConfig.PLACES_API_KEY

    // Log an error if apiKey is not set.
    if (apiKey.isEmpty() || apiKey == "DEFAULT_API_KEY") {
        Log.e("Places test", "No api key")
        finish()
        return
    }

    // Initialize the SDK
    Places.initializeWithNewPlacesApiEnabled(applicationContext, apiKey)

    // Create a new PlacesClient instance
    val placesClient = Places.createClient(this)
    

Java

    // Define a variable to hold the Places API key.
    String apiKey = BuildConfig.PLACES_API_KEY;

    // Log an error if apiKey is not set.
    if (TextUtils.isEmpty(apiKey) || apiKey.equals("DEFAULT_API_KEY")) {
      Log.e("Places test", "No api key");
      finish();
      return;
    }

    // Initialize the SDK
    Places.initializeWithNewPlacesApiEnabled(getApplicationContext(), apiKey);

    // Create a new PlacesClient instance
    PlacesClient placesClient = Places.createClient(this);
    

Places SDK for Android

调用 Places.initialize() 时传递 API 密钥:

Kotlin

    // Define a variable to hold the Places API key.
    val apiKey = BuildConfig.PLACES_API_KEY

    // Log an error if apiKey is not set.
    if (apiKey.isEmpty() || apiKey == "DEFAULT_API_KEY") {
        Log.e("Places test", "No api key")
        finish()
        return
    }

    // Initialize the SDK
    Places.initialize(applicationContext, apiKey)

    // Create a new PlacesClient instance
    val placesClient = Places.createClient(this)
    

Java

    // Define a variable to hold the Places API key.
    String apiKey = BuildConfig.PLACES_API_KEY;

    // Log an error if apiKey is not set.
    if (TextUtils.isEmpty(apiKey) || apiKey.equals("DEFAULT_API_KEY")) {
      Log.e("Places test", "No api key");
      finish();
      return;
    }

    // Initialize the SDK
    Places.initialize(getApplicationContext(), apiKey);

    // Create a new PlacesClient instance
    PlacesClient 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) 管理器来创建虚拟设备并安装模拟器。

后续步骤

配置项目后,您可以浏览示例应用