איך מגדירים פרויקט Android Studio

כדי להגדיר את האפליקציה לשימוש ב-Places SDK ל-Android, פועלים לפי השלבים הבאים. הם נדרשים בכל האפליקציות שמשתמשות ב-Places SDK ל-Android.

שלב 1: הגדרת Android Studio

במסמך הזה מתוארת סביבת פיתוח באמצעות Android Studio Hedgehog ו-Android Gradle plugin בגרסה 8.2.

שלב 2. הגדרת ה-SDK

ספריית Places SDK ל-Android זמינה דרך מאגר Maven של Google. כדי להוסיף את ה-SDK לאפליקציה:

  1. בקובץ settings.gradle.kts ברמה העליונה, כוללים את Gradle plugin portal,‏ Google Maven repository ו-Maven central repository בקטע pluginManagement. הבלוק pluginManagement חייב להופיע לפני כל הצהרה אחרת בסקריפט.
    pluginManagement {
        repositories {
            gradlePluginPortal()
            google()
            mavenCentral()
        }
    } 
  2. בקובץ settings.gradle.kts ברמה העליונה, צריך לכלול את מאגר Maven של Google ואת מאגר Maven המרכזי בקטע dependencyResolutionManagement:
    dependencyResolutionManagement {
        repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
        repositories {
            google()
            mavenCentral()
        }
    } 
  3. בקטע dependencies של קובץ build.gradle.kts ברמת המודול, מוסיפים תלות ב-Places SDK ל-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. בקובץ build.gradle.kts ברמת המודול, מגדירים את compileSdk ואת minSdk לערכים הבאים:

    Groovy

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

    Kotlin

    android {
        compileSdk = 34
    
        defaultConfig {
            minSdk = 23
            // ...
        }
    }
  5. בקטע buildFeatures בקובץ build.gradle ברמת המודול, מוסיפים את המחלקה BuildConfig, שמשמשת לגישה לערכי מטא-נתונים שמוגדרים בהמשך בשלב הזה:

    Groovy

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

    Kotlin

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

שלב 3: מוסיפים את מפתח ה-API לפרויקט

בקטע הזה מוסבר איך לאחסן את מפתח ה-API כך שהאפליקציה תוכל להפנות אליו בצורה מאובטחת. לא מומלץ להכניס את מפתח ה-API למערכת בקרת הגרסאות, ולכן אנחנו ממליצים לאחסן אותו בקובץ secrets.properties שנמצא בספריית הבסיס של הפרויקט. מידע נוסף על הקובץ secrets.properties זמין במאמר קובצי מאפיינים של Gradle.

כדי לייעל את המשימה הזו, מומלץ להשתמש בפלאגין של Secrets Gradle ל-Android.

כדי להתקין את הפלאגין Secrets Gradle ל-Android בפרויקט של מפות Google:

  1. ב-Android Studio, פותחים את הקובץ build.gradle.kts או build.gradle ברמה העליונה ומוסיפים את הקוד הבא לרכיב dependencies בקטע 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. פותחים את הקובץ build.gradle.kts או build.gradle ברמת המודול ומוסיפים את הקוד הבא לרכיב plugins.

    Kotlin

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

    Groovy

    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }
  3. בקובץ build.gradle.kts או build.gradle ברמת המודול, מוודאים שהערכים של targetSdk ו-compileSdk מוגדרים ל-34.
  4. מסנכרנים את הפרויקט עם Gradle.
  5. פותחים את הקובץ secrets.properties בספרייה ברמה העליונה ומוסיפים את הקוד הבא. מחליפים את הערך YOUR_API_KEY במפתח ה-API שלכם. מומלץ לשמור את המפתח בקובץ הזה כי secrets.properties לא נכלל בבדיקה במערכת בקרת גרסאות.
    PLACES_API_KEY=YOUR_API_KEY
  6. יוצרים את הקובץ local.defaults.properties בספרייה ברמה העליונה, באותה תיקייה שבה נמצא הקובץ secrets.properties, ואז מוסיפים את הקוד הבא.

    PLACES_API_KEY=DEFAULT_API_KEY

    המטרה של הקובץ הזה היא לספק מיקום גיבוי למפתח ה-API אם הקובץ secrets.properties לא נמצא, כדי שהגרסאות לא ייכשלו. זה יכול לקרות אם: משכפלים את האפליקציה ממערכת בקרת גרסאות שבה לא מופיע secrets.properties, ועדיין לא יצרתם קובץ secrets.properties באופן מקומי כדי לספק את מפתח ה-API.

  7. ב-Android Studio, פותחים את הקובץ build.gradle.kts או build.gradle ברמת המודול ועורכים את המאפיין secrets. אם המאפיין secrets לא קיים, מוסיפים אותו.

    עורכים את המאפיינים של הפלאגין כדי להגדיר את propertiesFileName לערך secrets.properties, את defaultPropertiesFileName לערך local.defaults.properties, וכל מאפיין אחר.

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

שלב 4. אתחול של לקוח Places API

מאחלים את Places SDK ל-Android בפעילות או ב-fragment. קודם צריך להחליט באיזו גרסה של ה-SDK להשתמש: Places SDK ל-Android או Places SDK ל-Android (חדש). מידע נוסף על גרסאות מוצרים זמין במאמר בחירת גרסת ה-SDK.

בדוגמה הבאה מוצג אופן האתחול של ה-SDK בשתי הגרסאות.

‫Places SDK ל-Android (חדש)

מעבירים את מפתח ה-API כששולחים קריאה אל 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 של מקומות ל-Android

מעבירים את מפתח ה-API כששולחים קריאה אל 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);
    

עכשיו אפשר להתחיל להשתמש ב-Places SDK ל-Android.

שלב 5: הגדרת מכשיר Android

כדי להריץ אפליקציה שמשתמשת ב-Places SDK ל-Android, צריך לפרוס אותה במכשיר Android או באמולטור Android שמבוסס על Android 5.0 ואילך וכולל את Google APIs.

  • כדי להשתמש במכשיר Android, פועלים לפי ההוראות במאמר הרצת אפליקציות במכשיר חומרה.
  • כדי להשתמש באמולטור Android, אפשר ליצור מכשיר וירטואלי ולהתקין את האמולטור באמצעות הכלי לניהול מכשירים וירטואליים (AVD) של Android שמגיע עם Android Studio.

השלבים הבאים

אחרי שמגדירים את הפרויקט, אפשר לעיין באפליקציות לדוגמה.