在安卓12 (SPB5.210812.002)的Pixel 4a上,如果用户只授权了大致位置权限,
FusedLocationProviderClient
将不会返回任何位置信息。当我将权限更改为精确位置权限时,便能够获取到位置信息。
在清单文件中我已经声明了粗略和精确位置权限,并在运行时请求了两者的权限。<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()
}
}
}