Android Studio 3.4
我正在使用FusedLocationProviderClient
获取纬度和经度的坐标。
但是,我正在测试的情况是用户在设置下关闭该位置。通常,再次打开任何位置数据都会清除该数据。
在以下代码段中,我试图通过请求位置更新来处理这种情况。但是,该应用程序不会获得任何最新更新,我希望请求超时。我用LocationResult
创建了setExpirationDuration
,认为如果将其设置为10000 ms,则可能会在10秒后超时。但是什么也没发生。
private fun getLocationFused() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION), permissionRequestCode)
}
else {
fusedLocationProviderClient.lastLocation.addOnSuccessListener(this) { location ->
if(location != null) {
forecastPresenter.requestWeatherForecast(location.latitude, location.longitude)
}
else {
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
forecastPresenter.requestWeatherForecast(locationResult.lastLocation.latitude, locationResult.lastLocation.longitude)
fusedLocationProviderClient.removeLocationUpdates(this)
}
}
val locationResult = LocationRequest()
locationResult.maxWaitTime = 10000
fusedLocationProviderClient.requestLocationUpdates(locationResult, locationCallback, null)
}
}.addOnFailureListener(this) {
println(it.message)
}.addOnCanceledListener(this) {
println("Cancelled")
}
}
}
如果事件在之后超时,那么将调用什么方法? onLocationResult
是否返回空locationResult
?
非常感谢您的任何建议,