Thiết lập dự án Android Studio

Để định cấu hình ứng dụng sử dụng Places SDK cho Android, hãy làm theo các bước sau. Đây là những yêu cầu bắt buộc đối với tất cả các ứng dụng sử dụng Places SDK for Android.

Bước 1: Thiết lập Android Studio

Tài liệu này mô tả một môi trường phát triển bằng Android Studio Hedgehogtrình bổ trợ Android cho Gradle phiên bản 8.2.

Bước 2. Thiết lập SDK

Thư viện Places SDK for Android có sẵn thông qua kho lưu trữ Maven của Google. Để thêm SDK vào ứng dụng, hãy làm như sau:

  1. Trong tệp settings.gradle.kts cấp cao nhất, hãy thêm cổng trình bổ trợ Gradle, kho lưu trữ Google Mavenkho lưu trữ trung tâm Maven trong khối pluginManagement. Khối pluginManagement phải xuất hiện trước mọi câu lệnh khác trong tập lệnh.
    pluginManagement {
        repositories {
            gradlePluginPortal()
            google()
            mavenCentral()
        }
    } 
  2. Trong tệp settings.gradle.kts cấp cao nhất, hãy thêm kho lưu trữ Maven của Googlekho lưu trữ trung tâm Maven trong khối dependencyResolutionManagement:
    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            google()
            mavenCentral()
        }
    } 
  3. Trong phần dependencies của tệp build.gradle.kts ở cấp mô-đun, hãy thêm một phần phụ thuộc vào Places SDK cho Android:

    Groovy

    dependencies {
        implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version"))
        implementation("com.google.android.libraries.places:places:3.5.0")
    }

    Kotlin

              dependencies {
    
        // Places and Maps SDKs
        implementation("com.google.android.libraries.places:places:4.3.1")
    }
  4. Trong tệp build.gradle.kts ở cấp mô-đun, hãy đặt compileSdkminSdk thành các giá trị sau:

    Groovy

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

    Kotlin

    android {
        compileSdk = 34
    
        defaultConfig {
            minSdk = 23
            // ...
        }
    }
  5. Trong phần buildFeatures của tệp build.gradle ở cấp mô-đun, hãy thêm lớp BuildConfig mà bạn dùng để truy cập vào các giá trị siêu dữ liệu được xác định sau trong quy trình này:

    Groovy

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

    Kotlin

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

Bước 3: Thêm khoá API vào dự án

Phần này mô tả cách lưu trữ khoá API để ứng dụng của bạn có thể tham chiếu một cách an toàn. Bạn không nên kiểm tra khoá API trong hệ thống kiểm soát phiên bản. Vì vậy, bạn nên lưu trữ khoá này trong tệp secrets.properties nằm trong thư mục gốc của dự án. Để biết thêm thông tin về tệp secrets.properties, hãy xem phần Tệp thuộc tính Gradle.

Để đơn giản hoá tác vụ này, bạn nên sử dụng Trình bổ trợ Secrets Gradle cho Android.

Cách cài đặt Trình bổ trợ Secrets Gradle cho Android trong dự án Google Maps:

  1. Trong Android Studio, hãy mở tệp build.gradle.kts hoặc build.gradle cấp cao nhất rồi thêm mã sau vào phần tử dependencies trong buildscript.

    Kotlin

    buildscript {
        dependencies {
            classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1")
        }
    }

    Groovy

    buildscript {
        dependencies {
            classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1"
        }
    }
  2. Mở tệp build.gradle.kts hoặc build.gradle ở cấp mô-đun rồi thêm đoạn mã sau vào phần tử plugins.

    Kotlin

    plugins {
        // ...
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }

    Groovy

    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }
  3. Trong tệp build.gradle.kts hoặc build.gradle ở cấp mô-đun, hãy đảm bảo rằng targetSdkcompileSdk được đặt thành 34.
  4. Đồng bộ hoá dự án của bạn với Gradle.
  5. Mở tệp secrets.properties trong thư mục cấp cao nhất, sau đó thêm đoạn mã sau. Thay thế YOUR_API_KEY bằng khoá API của bạn. Lưu trữ khoá của bạn trong tệp này vì secrets.properties không được đưa vào hệ thống quản lý phiên bản.
    PLACES_API_KEY=YOUR_API_KEY
  6. Tạo tệp local.defaults.properties trong thư mục cấp cao nhất (cùng thư mục với tệp secrets.properties), rồi thêm mã sau.

    PLACES_API_KEY=DEFAULT_API_KEY

    Mục đích của tệp này là cung cấp một vị trí sao lưu cho khoá API nếu không tìm thấy tệp secrets.properties để các bản dựng không bị lỗi. Điều này có thể xảy ra nếu bạn sao chép ứng dụng từ một hệ thống kiểm soát phiên bản bỏ qua secrets.properties và bạn chưa tạo tệp secrets.properties cục bộ để cung cấp khoá API.

  7. Trong Android Studio, hãy mở tệp build.gradle.kts hoặc build.gradle ở cấp mô-đun rồi chỉnh sửa thuộc tính secrets. Nếu thuộc tính secrets không tồn tại, hãy thêm thuộc tính đó.

    Chỉnh sửa các thuộc tính của trình bổ trợ để đặt propertiesFileName thành secrets.properties, đặt defaultPropertiesFileName thành local.defaults.properties và đặt mọi thuộc tính khác.

    Kotlin

    secrets {
        // To add your Maps API key to this project:
        // 1. If the secrets.properties file does not exist, create it in the same folder as the local.properties file.
        // 2. Add this line, where YOUR_API_KEY is your API key:
        //        MAPS_API_KEY=YOUR_API_KEY
        propertiesFileName = "secrets.properties"
    
        // A properties file containing default secret values. This file can be
        // checked in version control.
        defaultPropertiesFileName = "local.defaults.properties"
    }
            

    Groovy

    secrets {
        // To add your Maps API key to this project:
        // 1. If the secrets.properties file does not exist, create it in the same folder as the local.properties file.
        // 2. Add this line, where YOUR_API_KEY is your API key:
        //        MAPS_API_KEY=YOUR_API_KEY
        propertiesFileName = "secrets.properties"
    
        // A properties file containing default secret values. This file can be
        // checked in version control.
        defaultPropertiesFileName = "local.defaults.properties"
    }
            

Bước 4. Khởi chạy ứng dụng Places API

Khởi động Places SDK for Android trong một hoạt động hoặc mảnh. Trước tiên, bạn phải quyết định sử dụng phiên bản SDK nào: Places SDK for Android hoặc Places SDK for Android (Mới). Để biết thêm thông tin về các phiên bản sản phẩm, hãy xem bài viết Chọn phiên bản SDK.

Ví dụ sau đây cho thấy cách khởi chạy SDK cho cả hai phiên bản.

Places SDK for Android (Mới)

Truyền khoá API khi gọi Places.initializeWithNewPlacesApiEnabled():

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);
    

SDK Địa điểm dành cho Android

Truyền khoá API khi gọi Places.initializeWithNewPlacesApiEnabled():

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);
    

Giờ đây, bạn đã sẵn sàng bắt đầu sử dụng Places SDK cho Android!

Bước 5: Thiết lập thiết bị Android

Để chạy một ứng dụng sử dụng Places SDK cho Android, bạn phải triển khai ứng dụng đó trên một thiết bị Android hoặc trình mô phỏng Android dựa trên Android 5.0 trở lên và có các API của Google.

  • Để sử dụng thiết bị Android, hãy làm theo hướng dẫn trong phần Chạy ứng dụng trên thiết bị phần cứng.
  • Để sử dụng trình mô phỏng Android, bạn có thể tạo một thiết bị ảo và cài đặt trình mô phỏng bằng cách sử dụng Trình quản lý thiết bị ảo Android (AVD) đi kèm với Android Studio.

Các bước tiếp theo

Sau khi định cấu hình dự án, bạn có thể khám phá các ứng dụng mẫu.