原答案
发生这种情况是因为FusedLocationProviderApi
在最新版本的 Google Play 服务中已弃用。你可以检查一下here https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi。官方指南现在建议使用融合位置提供者客户端 https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient。你可以找到详细的指南here https://developer.android.com/training/location/retrieve-current.html#play-services.
例如在里面onCreate()
or onViewCreated()
创建一个FusedLocationProviderClient
实例
Kotlin
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext())
要请求最后的已知位置,您所要做的就是致电
fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let { it: Location ->
// Logic to handle location object
} ?: kotlin.run {
// Handle Null case or Request periodic location update https://developer.android.com/training/location/receive-location-updates
}
}
Java
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext());
and
fusedLocationClient.getLastLocation().addOnSuccessListener(requireActivity(), location -> {
if (location != null) {
// Logic to handle location object
} else {
// Handle null case or Request periodic location update https://developer.android.com/training/location/receive-location-updates
}
});
很简单,不是吗?
重要更新(2017 年 10 月 24 日):
昨天谷歌更新了其官方开发者页面一个警告 https://developer.android.com/training/location/retrieve-current.html说的是
请继续使用 FusedLocationProviderApi 类,并且不要迁移到 FusedLocationProviderClient 类,直到 Google Play 服务版本 12.0.0 可用(预计将于 2018 年初发布)。在 12.0.0 版本之前使用 FusedLocationProviderClient 会导致客户端应用程序崩溃设备上的 Google Play 服务已更新。对此造成的任何不便,我们深表歉意。
So I think we should continue using the deprecated LocationServices.FusedLocationApi
until Google resolves the issue.
最新更新(2017 年 11 月 21 日):
The warning is gone now. Google Play services 11.6 November 6, 2017, release note https://developers.google.com/android/guides/releases says : I think Play Services won't crash when it updates itself in the background. So we can use new FusedLocationProviderClient
now.