Android 스튜디오 프로젝트 설정

Android용 Places SDK를 사용하도록 앱을 구성하려면 다음 단계를 따르세요. Android용 Places SDK를 사용하는 모든 앱에는 이 속성이 필요합니다.

1단계: Android 스튜디오 설정

이 문서에서는 Android 스튜디오 HedgehogAndroid Gradle 플러그인 버전 8.2를 사용하는 개발 환경을 설명합니다.

2단계: SDK 설정

Android용 Places SDK 라이브러리는 Google의 Maven 저장소를 통해 사용할 수 있습니다. 앱에 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 섹션에서 Android용 Places SDK에 종속 항목을 추가합니다.

    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용 Secrets Gradle 플러그인을 사용하는 것이 좋습니다.

Google 지도 프로젝트에 Android용 Secrets Gradle 플러그인을 설치하려면 다음 단계를 따르세요.

  1. Android 스튜디오에서 최상위 수준 build.gradle 또는 build.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

    이 파일의 목적은 secrets.properties 파일이 없는 경우 빌드에 실패하지 않도록 API 키의 백업 위치를 제공하는 것입니다. 이는 버전 제어 시스템에서 secrets.properties가 빠진 앱을 복제하거나 API 키를 제공하는 secrets.properties 파일을 아직 로컬에서 생성하지 않은 경우 발생할 수 있습니다.

  8. 파일을 저장합니다.
  9. Android 스튜디오에서 모듈 수준 build.gradle 또는 build.gradle.kts 파일을 열고 secrets 속성을 수정합니다. secrets 속성이 없으면 추가합니다.

    플러그인 속성을 수정하여 propertiesFileNamesecrets.properties로 설정하고 defaultPropertiesFileNamelocal.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 클라이언트 초기화

활동 또는 프래그먼트 내에서 Android용 Places SDK를 초기화합니다. 먼저 Android용 Places SDK 또는 Android용 Places SDK (신규) 중 어떤 버전의 SDK를 사용할지 결정해야 합니다. 제품 버전에 관한 자세한 내용은 SDK 버전 선택을 참고하세요.

다음 예는 두 버전 모두에서 SDK를 초기화하는 방법을 보여줍니다.

Android용 Places SDK (신규)

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

Android용 Places SDK

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

이제 Android용 Places SDK를 사용할 준비가 되었습니다.

5단계: Android 기기 설정

Android용 Places SDK를 사용하는 앱을 실행하려면 Google API를 포함하는 Android 4.0 이상의 Android 기기나 Android Emulator에 SDK를 배포해야 합니다.

  • Android 기기를 사용하려면 하드웨어 기기에서 앱 실행하기의 안내를 따르세요.
  • Android Emulator를 사용하려면 Android 스튜디오와 함께 제공되는 Android Virtual Device(AVD) Manager를 이용해 가상 기기를 만들고 에뮬레이터를 설치하면 됩니다.

다음 단계

프로젝트가 구성된 후 샘플 앱을 살펴볼 수 있습니다.