From c61412520dff34e746ea8f5562164ffea3f99d0e Mon Sep 17 00:00:00 2001 From: Maxime NATUREL Date: Tue, 3 May 2022 16:55:14 +0200 Subject: [PATCH] Debouncing location updates --- .../app/features/location/LocationTracker.kt | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt b/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt index 6f9d4b7870..2a5dff57d5 100644 --- a/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt +++ b/vector/src/main/java/im/vector/app/features/location/LocationTracker.kt @@ -44,6 +44,8 @@ class LocationTracker @Inject constructor( private var hasGpsProviderLiveLocation = false + private var lastLocationUpdateMillis: Long? = null + private var lastLocation: LocationData? = null @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) @@ -84,7 +86,7 @@ class LocationTracker @Inject constructor( } else { Timber.d("## LocationTracker. lastKnownLocation: ${latestKnownLocation.provider}") } - notifyLocation(latestKnownLocation, isLive = false) + notifyLocation(latestKnownLocation) } } } @@ -123,14 +125,10 @@ class LocationTracker @Inject constructor( } else { Timber.d("## LocationTracker. onLocationChanged: ${location.provider}") } - notifyLocation(location, isLive = true) - } - private fun notifyLocation(location: Location, isLive: Boolean) { - Timber.d("## LocationTracker. notify location") when (location.provider) { LocationManager.GPS_PROVIDER -> { - hasGpsProviderLiveLocation = isLive + hasGpsProviderLiveLocation = true } else -> { if (hasGpsProviderLiveLocation) { @@ -140,9 +138,22 @@ class LocationTracker @Inject constructor( } } } + + val nowMillis = System.currentTimeMillis() + val elapsedMillis = nowMillis - (lastLocationUpdateMillis ?: 0) + if (elapsedMillis >= MIN_TIME_TO_UPDATE_LOCATION_MILLIS) { + lastLocationUpdateMillis = nowMillis + notifyLocation(location) + } else { + Timber.d("## LocationTracker. ignoring location: update is too fast") + } + } + + private fun notifyLocation(location: Location) { + Timber.d("## LocationTracker. notify location") val locationData = location.toLocationData() lastLocation = locationData - callbacks.forEach { it.onLocationUpdate(locationData) } + callbacks.forEach { it.onLocationUpdate(location.toLocationData()) } } override fun onProviderDisabled(provider: String) {