首页 > 解决方案 > 重新启动后位置更新需要很长时间,使用 FusedLocationProviderClient

问题描述

我正在使用FusedLocationProviderClient来访问lastLocation用户的。如果它为空,我正在等待requestLocationUpdates返回。

我已经通过重新启动设备在我的 Pixel 3a 上对此进行了测试,这会清除最后一个位置,但是返回一个位置需要 2 分钟以上。

这是我的代码。我究竟做错了什么?

    private fun onLocationPermissionGranted() {
        val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(
            requireContext()
        )

        fusedLocationProviderClient.flushLocations()

        Log.i("Jamie", "Attempting to access last location")

        val locationRequest = LocationRequest.create()
        locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
        locationRequest.interval = 5000
        locationRequest.numUpdates = 1

        val callback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                Log.i("Jamie", "Calling location permission granted again")
                onLocationPermissionGranted()
            }
        }

        fusedLocationProviderClient.lastLocation
            .addOnSuccessListener { location: Location? ->
                Log.i("Jamie", "FusedLocation onsuccess called")
                if (location == null) {
                    Log.i("Jamie", "location null")
                }

                location?.let {
                    fusedLocationProviderClient.removeLocationUpdates(callback)
                    Log.i("Jamie", "Location received")
                    this.map.isMyLocationEnabled = true
                    viewModel.currentLocation = location
                    updateCamera(location.latitude, location.longitude)
                }
            }

        fusedLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper())
    }
2020-08-31 14:04:33.834 3780-3780/com.redacted I/Jamie: Attempting to access last location
2020-08-31 14:04:34.547 3780-3780/com.redacted I/Jamie: FusedLocation onsuccess called
2020-08-31 14:04:34.547 3780-3780/com.redacted I/Jamie: location null
2020-08-31 14:06:50.404 3780-3780/com.redacted I/Jamie: Calling location permission granted again
2020-08-31 14:06:50.404 3780-3780/com.redacted I/Jamie: Attempting to access last location
2020-08-31 14:06:50.517 3780-3780/com.redacted I/Jamie: FusedLocation onsuccess called
2020-08-31 14:06:50.517 3780-3780/com.redacted I/Jamie: Location received

标签: androidkotlinfusedlocationproviderclient

解决方案


推荐阅读