获取最近一次的已知位置
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
使用 Google Play 服务地理位置 API,您的应用可以请求获取用户设备最近一次的已知位置。在大多数情况下,您感兴趣的是用户的当前位置,通常也就是设备最近一次的已知位置。
具体来说,使用一体化位置信息提供程序可检索设备最近一次的已知位置。一体化位置信息提供程序是 Google Play 服务中的一个地理位置 API。它负责管理底层定位技术,并提供一个简单的 API,以便您指定准确度高或耗电量低等比较笼统的要求。它还可以优化设备的电池电量消耗。
注意:当您的应用在后台运行时,获取位置信息访问权限对应用的核心功能至关重要,但同时需要向用户提供适当的声明。
本课向您介绍如何使用一体化位置信息提供程序中的 getLastLocation()
方法发出获取设备位置信息的单个请求。
设置 Google Play 服务
如需访问一体化位置信息提供程序,您的应用开发项目必须包含 Google Play 服务。通过 SDK 管理器下载 Google Play 服务组件并进行安装,然后将内容库添加至您的项目。如需了解详情,请参阅介绍如何设置 Google Play 服务的指南。
指定应用权限
如果应用的功能需要使用位置信息服务,应用必须根据这些功能的使用场景来请求位置信息权限。
创建位置信息服务客户端
在 Activity 的 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()
方法会返回一个 Task
,供您用来获取具有地理位置经纬度坐标的 Location
对象。在以下情况下,该位置信息对象可能为 null
:
- 设备设置中关闭了位置信息服务。即使之前检索到了最近一次的位置信息,结果也可能为
null
,因为停用位置信息服务也会清除缓存。
- 设备从未记录自己的位置信息。新设备或者已经恢复为出厂设置的设备可能会发生此情况。
- 设备上的 Google Play 服务已经重启,且在服务重启后,没有已请求位置信息的活跃一体化位置信息提供程序客户端。为避免这种情况,您可以创建新客户端并自行请求位置信息更新。如需了解详情,请参阅请求位置信息更新。
选择最佳位置信息估算值
FusedLocationProviderClient
提供了多种检索设备位置信息的方法。根据应用的使用场景,从以下选项中选择一项:
getLastLocation()
可更快地获取位置信息估算值,并最大限度地减少应用对电池用量的消耗。但是,如果最近没有其他客户端主动使用位置信息,则位置信息可能会过时。
getCurrentLocation()
可以更一致、更及时地获取更准确的位置信息。不过,这种方法会导致系统在设备上进行主动位置信息计算。
我们推荐使用这种方法来获取最新位置信息,并建议您尽可能使用这种方法。与使用 requestLocationUpdates()
自行启动和管理位置信息更新等替代方案相比,这种方法更安全。如果您的应用调用 requestLocationUpdates()
,则在无法获取位置信息,或者获取新位置后请求未正确停止时,会消耗大量电量。
其他资源
如需详细了解如何在 Android 中获取当前位置,请查看以下资料:
示例
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-21。
[null,null,["最后更新时间 (UTC):2025-08-21。"],[],[],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."]]