@@ -46,6 +46,7 @@ class LocationManager(private val context: Context, override val lifecycle: Life
46
46
private var coarsePendingIntent: PendingIntent ? = null
47
47
private val postProcessor by lazy { LocationPostProcessor () }
48
48
private val lastLocationCapsule by lazy { LastLocationCapsule (context) }
49
+ private var lastGpsLocation: Location ? = null
49
50
val database by lazy { LocationAppsDatabase (context) }
50
51
private val requestManager by lazy { LocationRequestManager (context, lifecycle, postProcessor, database) { onRequestManagerUpdated() } }
51
52
private val gpsLocationListener by lazy { LocationListenerCompat { updateGpsLocation(it) } }
@@ -224,12 +225,29 @@ class LocationManager(private val context: Context, override val lifecycle: Life
224
225
}
225
226
}
226
227
228
+ private fun Location.isUnreasonablyFarFromRecentGpsLocation (): Boolean {
229
+ val gpsLocation = lastGpsLocation ? : return false
230
+
231
+ // Ignore GPS location that is too old compared to this location
232
+ if (gpsLocation.elapsedMillis < elapsedMillis + MAX_FINE_UPDATE_INTERVAL ) return false
233
+
234
+ val distance = distanceTo(gpsLocation)
235
+ if (distance > min(2 * gpsLocation.accuracy, MIN_UNREASONABLE_DISTANCE_FROM_GPS )) {
236
+ Log .d(TAG , String .format(" Unreasonable location %s vs gps (accuracy %.0f): distance %.0f" ,
237
+ this .provider, gpsLocation.accuracy, distance))
238
+ return true
239
+ }
240
+ return false
241
+ }
242
+
227
243
fun updateNetworkLocation (location : Location ) {
228
244
val lastLocation = lastLocationCapsule.getLocation(GRANULARITY_FINE , Long .MAX_VALUE )
229
245
230
246
// Ignore outdated location
231
247
if (lastLocation != null && location.elapsedMillis + UPDATE_CLIFF_MS < lastLocation.elapsedMillis) return
232
248
249
+ if (location.isUnreasonablyFarFromRecentGpsLocation()) return
250
+
233
251
if (lastLocation == null ||
234
252
lastLocation.accuracy > location.accuracy ||
235
253
lastLocation.elapsedMillis + min(requestManager.intervalMillis * 2 , UPDATE_CLIFF_MS ) < location.elapsedMillis ||
@@ -242,6 +260,7 @@ class LocationManager(private val context: Context, override val lifecycle: Life
242
260
243
261
fun updateGpsLocation (location : Location ) {
244
262
lastLocationCapsule.updateFineLocation(location)
263
+ lastGpsLocation = location
245
264
sendNewLocation()
246
265
}
247
266
@@ -324,5 +343,6 @@ class LocationManager(private val context: Context, override val lifecycle: Life
324
343
const val MAX_FINE_UPDATE_INTERVAL = 10_000L
325
344
const val EXTENSION_CLIFF_MS = 10_000L
326
345
const val UPDATE_CLIFF_MS = 30_000L
346
+ const val MIN_UNREASONABLE_DISTANCE_FROM_GPS = 1_000f // 1 kilometer
327
347
}
328
348
}
0 commit comments