在搭载 Android 12 (SPB5.210812.002) 的 Pixel 4a 上,当用户授予大致位置权限时,不会从FusedLocationProviderClient
. 当我将权限更改为确切位置权限时,我就可以获得位置。
我在 Manifest 中同时拥有粗略和精细的位置权限,并在运行时同时请求这两者。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
一旦获得任一许可,我就会请求lastKnownLocation
,以及请求位置更新。有了精确的位置许可,我很快就能得到位置,但当用户给出大致的位置许可时却没有。
对于位置请求优先级,我已经尝试过LocationRequest.PRIORITY_HIGH_ACCURACY
和LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
。
在 Android 9 上,一切都按预期工作,所以我猜这与Android 12 中引入的精确/近似位置权限有关。
这是我的代码的一部分:
private val fusedLocationClient by lazy {
LocationServices.getFusedLocationProviderClient(requireContext())
}
private val cts: CancellationTokenSource = CancellationTokenSource()
private val locationRequest = LocationRequest()
.setPriority(LOCATION_REQUEST_PRIORITY)
.setFastestInterval(MIN_TIME_BETWEEN_STAMPS_IN_MILLIS) // 1000
.setInterval(TIME_BETWEEN_STAMPS_IN_MILLIS) // 10000
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult?.locations?.firstOrNull()?.let {
userLocation = it
onUserLocationUpdated()
}
}
}
private fun onLocationPermissionGranted() {
if (!requireContext().isLocationEnabled()) {
requireContext().showLocationPermissionRequiredDialog {
onBackPressed()
}
} else {
try {
getCurrentLocation()
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
} catch (t: Throwable) {
onBackPressed()
}
}
}
private fun getCurrentLocation() {
fusedLocationClient.getCurrentLocation(
LOCATION_REQUEST_PRIORITY,
cts.token
).addOnSuccessListener { location: Location? ->
if (location != null) {
userLocation = location
onUserLocationUpdated()
}
}
}