마지막으로 알려진 위치 가져오기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Google Play 서비스 Location API를 사용하여 앱에서 마지막으로 알려진 사용자 기기의 위치를 요청할 수 있습니다. 대부분의 경우 사용자의 현재 위치에 관심이 있으며 사용자의 현재 위치는 일반적으로 마지막으로 알려진 기기의 위치와 같습니다.
마지막으로 알려진 기기의 위치를 가져오려면 통합 위치 정보 제공자를 사용하세요. 통합 위치 정보 제공자는 Google Play 서비스의 Location API 중 하나입니다. 기본 위치 기술을 관리하고 단순한 API를 제공하므로, 높은 수준으로 요구사항(높은 정확성이나 저전력 등)을 지정할 수 있습니다.
이 API는 기기의 배터리 전력 사용을 최적화해 줍니다.
참고: 앱이 백그라운드에서 실행 중일 때 위치에 액세스하는 기능은 앱의 핵심 기능에 중요한 영향을 주며 사용자에게 적절하게 공개됩니다.
이 과정에서는 통합 위치 정보 제공자에서 getLastLocation()
메서드를 사용하여 기기 위치를 한 번 요청하는 방법을 설명합니다.
Google Play 서비스 설정
통합 위치 정보 제공자에 액세스하려면 앱의 개발 프로젝트에 Google Play 서비스를 포함해야 합니다. SDK Manager를 통해 Google Play 서비스 구성요소를 다운로드 및 설치하고 프로젝트에 라이브러리를 추가합니다. 자세한 내용은 Google Play 서비스 설정 가이드를 참조하세요.
앱 권한 지정
위치 서비스를 사용하는 기능이 있는 앱은 이러한 기능의 사용 사례에 따라 위치 정보 액세스 권한을 요청해야 합니다.
위치 서비스 클라이언트 만들기
다음 코드 스니펫과 같이 활동의 onCreate()
메서드에서 통합 위치 정보 제공자 클라이언트의 인스턴스를 만드세요.
Kotlin
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
Java
private FusedLocationProviderClient fusedLocationClient;
// ..
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
마지막으로 알려진 위치 가져오기
위치 서비스 클라이언트를 만든 후 마지막으로 알려진 사용자 기기의 위치를 가져올 수 있습니다. 앱이 여기에 연결된 경우 통합 위치 정보 제공자의 getLastLocation()
메서드를 사용하여 기기 위치를 가져올 수 있습니다. 이 호출로 반환되는 위치의 정밀도는 위치 정보 액세스 권한 요청 방법에 관한 가이드에 설명된 대로 앱 매니페스트에 입력한 권한 설정에 따라 결정됩니다.
마지막으로 알려진 위치를 요청하려면 getLastLocation()
메서드를 호출하세요. 다음 코드 스니펫은 요청 및 간단한 응답 처리 방법을 보여줍니다.
Kotlin
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location. In some rare situations this can be null.
}
Java
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
getLastLocation()
메서드는 지리적 위치의 위도 및 경도 좌표가 있는 Location
객체를 가져오는 데 사용할 수 있는 Task
를 반환합니다. 다음 상황에서는 위치 객체가 null
일 수 있습니다.
- 기기 설정에서 위치가 사용 중지되어 있습니다. 위치를 사용 중지하면 캐시도 지워지므로 이전에 마지막 위치를 가져온 경우에도 결과는
null
일 수 있습니다.
- 기기에서 위치를 기록한 적이 없습니다. 예를 들면 새 기기이거나 기본 설정으로 복원된 기기일 수 있습니다.
- 기기의 Google Play 서비스가 다시 시작되었으며 서비스가 다시 시작된 후 위치를 요청한 활성 통합 위치 정보 제공자 클라이언트가 없습니다. 이러한 상황이 발생하지 않도록 새 클라이언트를 만들고 직접 위치 업데이트를 요청할 수 있습니다. 자세한 내용은 위치 업데이트 요청을 참고하세요.
최적의 위치 추정치 선택
FusedLocationProviderClient
는 기기 위치 정보를 가져오는 여러 메서드를 제공합니다. 앱의 사용 사례에 따라 다음 중 하나를 선택합니다.
getLastLocation()
은 위치 추정치를 더 빠르게 가져오고 앱의 배터리 사용량을 최소화합니다. 그러나 최근에 다른 클라이언트가 적극적으로 위치를 사용하지 않은 경우 위치 정보가 최신이 아닐 수 있습니다.
getCurrentLocation()
은 더 최신 상태이고 정확한 위치를 더 일관되게 가져옵니다. 그러나 이 메서드를 사용하면 기기에서 활성 위치 계산이 발생할 수 있습니다.
이 메서드는 가능한 경우 최신 위치를 가져오는 데 권장되는 방법이며 requestLocationUpdates()
를 사용하여 직접 위치 업데이트를 시작하고 관리하는 것보다 안전합니다. 앱에서 requestLocationUpdates()
를 호출하는 경우 위치를 사용할 수 없거나 최신 위치를 가져온 후 요청이 정확하게 중지되지 않으면 앱이 전력을 많이 소모할 수도 있습니다.
추가 리소스
Android에서 현재 위치를 가져오는 방법에 관한 자세한 내용은 다음 자료를 참고하세요.
샘플
- 샘플 앱: 현재 위치를 가져올 때의 권장사항을 보여줍니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-21(UTC)
[null,null,["최종 업데이트: 2025-08-21(UTC)"],[],[],null,["# Get the last known location\n\nUsing the Google Play services location APIs, your app can request the last\nknown location of the user's device. In most cases, you are interested in the\nuser's current location, which is usually equivalent to the last known\nlocation of the device.\n\nSpecifically, use the\n[fused\nlocation provider](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html) to retrieve the device's last known location. The fused\nlocation provider is one of the location APIs in Google Play services. It\nmanages the underlying location technology and provides a simple API so that\nyou can specify requirements at a high level, like high accuracy or low power.\nIt also optimizes the device's use of battery power. \n**Note:** When your app is running in the background,\n[access to location](/training/location/background) should be\ncritical to the core functionality of the app and is accompanied with proper\ndisclosure to users.\n\nThis lesson shows you how to make a single request for the location of a\ndevice using the\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod in the fused location provider.\n\nSet up Google Play services\n---------------------------\n\nTo access the fused location provider, your app's development project must\ninclude Google Play services. Download and install the Google Play services\ncomponent via the [SDK\nManager](/tools/help/sdk-manager) and add the library to your project. For details, see the guide to\n[Setting Up Google Play\nServices](/google/play-services/setup).\n\nSpecify app permissions\n-----------------------\n\nApps whose features use location services must\n[request location permissions](/training/location/permissions),\ndepending on the use cases of those features.\n\nCreate location services client\n-------------------------------\n\nIn your activity's [onCreate()](/reference/android/app/Activity#onCreate(android.os.Bundle)) method,\ncreate an instance of the Fused Location Provider Client as the following code snippet shows. \n\n### Kotlin\n\n```kotlin\nprivate lateinit var fusedLocationClient: FusedLocationProviderClient\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)\n}\n```\n\n### Java\n\n```java\nprivate FusedLocationProviderClient fusedLocationClient;\n\n// ..\n\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n // ...\n\n fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);\n}\n```\n\nGet the last known location\n---------------------------\n\nOnce you have created the Location Services client\nyou can get the last known location of a user's device. When your app is\nconnected to these you can use the fused location provider's\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod to retrieve the device location. The precision of the location returned\nby this call is determined by the permission setting you put in your app\nmanifest, as described in the guide on how to\n[request location permissions](/training/location/permissions).\n\nTo request the last known location, call the\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod. The following code snippet illustrates the request and a simple handling of the\nresponse: \n\n### Kotlin\n\n```kotlin\nfusedLocationClient.lastLocation\n .addOnSuccessListener { location : Location? -\u003e\n // Got last known location. In some rare situations this can be null.\n }\n```\n\n### Java\n\n```java\nfusedLocationClient.getLastLocation()\n .addOnSuccessListener(this, new OnSuccessListener\u003cLocation\u003e() {\n @Override\n public void onSuccess(Location location) {\n // Got last known location. In some rare situations this can be null.\n if (location != null) {\n // Logic to handle location object\n }\n }\n });\n```\n\nThe\n[`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#getLastLocation())\nmethod returns a [`Task`](https://developers.google.com/android/reference/com/google/android/gms/tasks/Task)\nthat you can use to get a\n[`Location`](/reference/android/location/Location)\nobject with the latitude and longitude coordinates of a\ngeographic location. The location object may be `null` in the\nfollowing situations:\n\n- Location is turned off in the device settings. The result could be `null` even if the last location was previously retrieved because disabling location also clears the cache.\n- The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.\n- Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see [Request location\n updates](/training/location/receive-location-updates).\n\nChoose the best location estimate\n---------------------------------\n\nThe `FusedLocationProviderClient` provides several methods to retrieve device\nlocation information. Choose from one of the following, depending on your app's\nuse case:\n\n- [`getLastLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getLastLocation()) gets a location estimate more quickly and minimizes battery usage that can be attributed to your app. However, the location information might be out of date, if no other clients have actively used location recently.\n- [`getCurrentLocation()`](https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken))\n gets a fresher, more accurate location more consistently. However, this method\n can cause active location computation to occur on the device\n\n This is the recommended way to get a fresh location, whenever possible, and\n is safer than alternatives like starting and managing location updates\n yourself using `requestLocationUpdates()`. If your app calls\n `requestLocationUpdates()`, your app can sometimes consume large amounts of\n power if location isn't available, or if the request isn't stopped correctly\n after obtaining a fresh location.\n\nAdditional resources\n--------------------\n\nFor more information about fetching current location in Android, view the\nfollowing materials:\n\n### Samples\n\n- [Sample app](https://github.com/android/platform-samples/tree/main/samples/location/src/main/java/com/example/platform/location/currentLocation) to demonstrate best practices while fetching current location."]]