Skip to content

Colota - Android GPS Location tracker

fix(tracking): re-register location updates when the active stream goes quiet (#586)

Max Dietriche4d371b0707e
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
index f43efb38..7f8c505e 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
@@ -65,6 +65,7 @@ class LocationForegroundService : Service() {
@Volatile private var locationRestartJob: Job? = null
@Volatile private var trackingHeartbeatJob: Job? = null
@Volatile private var lastFixAtMs: Long = 0L
+ @Volatile private var lastFixAtUptimeMs: Long = 0L
@Volatile private var motionDetector: MotionStateDetector? = null
@Volatile private var lastKnownLocation: Location? = null
@@ -160,6 +161,11 @@ class LocationForegroundService : Service() {
/** The stream counts as stalled after this many tracking intervals without a fix (floored at
* [PAUSE_WATCHDOG_INTERVAL_MS]), so a long interval isn't probed more often than configured. */
private const val PAUSE_WATCHDOG_STALL_INTERVALS = 2
+ /** Tracking intervals without a fix before the active stream is re-registered. */
+ private const val ACTIVE_STALL_INTERVALS = 5
+ /** Floor under that: several minutes without a fix is normal on a short interval, so a
+ * tighter floor would re-register during ordinary sleep. */
+ private const val ACTIVE_STALL_FLOOR_MS = 10 * 60_000L
const val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"
const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"
@@ -465,11 +471,13 @@ class LocationForegroundService : Service() {
return
}
lastFixAtMs = SystemClock.elapsedRealtime()
+ lastFixAtUptimeMs = SystemClock.uptimeMillis()
handleLocationUpdate(location)
}
}
locationUpdateCallback = callback
lastFixAtMs = SystemClock.elapsedRealtime()
+ lastFixAtUptimeMs = SystemClock.uptimeMillis()
if (deviceInfoHelper.isBatteryCritical()) {
val (level, _) = deviceInfoHelper.getCachedBatteryStatus()
@@ -550,7 +558,7 @@ class LocationForegroundService : Service() {
private fun isLocationUpdatesRegistered(): Boolean = locationUpdateCallback != null
/** Logs a state snapshot every 5 minutes so silent stalls and pause/stop gaps are visible
- * in user-exported logs. Data-only; no recovery action. */
+ * in user-exported logs, and re-registers a stream that has gone quiet while active. */
private fun startTrackingHeartbeatLogger() {
trackingHeartbeatJob?.cancel()
val scope = serviceScope ?: return
@@ -571,10 +579,33 @@ class LocationForegroundService : Service() {
} catch (e: Exception) {
AppLogger.w(TAG, "Heartbeat snapshot failed: ${e.message}")
}
+ try {
+ withContext(Dispatchers.Main) { recoverStalledStream() }
+ } catch (e: CancellationException) {
+ throw e // recovery cancels this job on purpose; swallowing it would leave two loops
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Stall recovery failed: ${e.message}")
+ }
}
}
}
+ /** Re-registers the stream after [ACTIVE_STALL_INTERVALS] intervals of silence. The pause
+ * watchdog only probes inside a zone, so a stream that dies while active stays dead. */
+ private fun recoverStalledStream() {
+ if (!isLocationUpdatesRegistered() || insidePauseZone || isWifiPaused || isMotionlessPaused) return
+ // The OS hands out no fixes while location is off, and the request survives the toggle.
+ if (!deviceInfoHelper.isLocationEnabled()) return
+ // Awake time, not wall clock: deep sleep produces no fixes by design.
+ val awakeSinceLastFix = SystemClock.uptimeMillis() - lastFixAtUptimeMs
+ val stallThresholdMs = maxOf(ACTIVE_STALL_FLOOR_MS, config.interval * ACTIVE_STALL_INTERVALS)
+ if (awakeSinceLastFix < stallThresholdMs) return
+ val wallSinceLastFix = SystemClock.elapsedRealtime() - lastFixAtMs
+ AppLogger.w(TAG, "Stream quiet ${awakeSinceLastFix / 1000}s awake (${wallSinceLastFix / 1000}s wall) while active - re-registering location updates")
+ stopLocationUpdates()
+ setupLocationUpdates()
+ }
+
/** Wifi and motionless are holds inside a zone pause, so they're checked first. Without
* PAUSED(zone) a latched pause reads as ACTIVE in an exported log. */
private fun trackingStateLabel(): String = when {
@@ -782,6 +813,10 @@ class LocationForegroundService : Service() {
}
ensureMotionDetectorRunning()
+ // Resume on state, not on a flag transition: a restore that dropped a stale motionless hold
+ // leaves no request behind, and a lightweight action never runs handleStart to make one.
+ if (!isLocationUpdatesRegistered()) maybeResumeGps()
+
if (zone.heartbeatEnabled && (heartbeatJob == null || heartbeatChanged)) {
val firstDelayMs =
if (heartbeatJustEnabled) 0L else remainingHeartbeatDelay(zone.heartbeatIntervalMinutes)
@@ -1483,8 +1518,13 @@ class LocationForegroundService : Service() {
// Wakelock holds the CPU across the async fix - the alarm's wake window ends here, and a foreground service won't.
val wakeLock = acquireHeartbeatWakeLock()
requestFreshOrLastLocation { location, _ ->
- if (location != null) handleLocationUpdate(location)
- else AppLogger.d(TAG, "Stationary heartbeat: no usable fix")
+ if (location != null) {
+ // Bypasses the provider callback, so stamp here or a stationary profile, which
+ // gets no OS-pushed fixes by design, reads as a dead stream.
+ lastFixAtMs = SystemClock.elapsedRealtime()
+ lastFixAtUptimeMs = SystemClock.uptimeMillis()
+ handleLocationUpdate(location)
+ } else AppLogger.d(TAG, "Stationary heartbeat: no usable fix")
if (wakeLock?.isHeld == true) wakeLock.release()
}
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
index dc3ea4dc..ea9faa47 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
@@ -1017,6 +1017,115 @@ class LocationForegroundServiceTest {
verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }
}
+ // =========================================================================
+ // Active-stream stall recovery
+ // =========================================================================
+
+ @Test
+ fun `re-registers the location stream after it goes quiet while active`() = runServiceTest {
+ // The pause watchdog only probes inside a zone, so a stream that dies while active
+ // otherwise stays dead
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtUptimeMs", -700_000L) // ~11.6 min awake, past the 10-min floor
+
+ invokeRecoverStalledStream()
+
+ verify { locationProvider.removeLocationUpdates(any()) }
+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `tolerates a doze-length gap on a short interval`() = runServiceTest {
+ // Several minutes without a fix is normal on a 5s interval; the floor keeps that from
+ // reading as a fault
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtUptimeMs", -420_000L) // 7 min awake
+
+ invokeRecoverStalledStream()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `does not count a night of deep sleep as silence`() = runServiceTest {
+ // 8h of wall clock but no awake time: the phone was suspended, so it produced no fixes
+ // by design
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtMs", -8 * 60 * 60_000L)
+ setField("lastFixAtUptimeMs", -10_000L)
+
+ invokeRecoverStalledStream()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `does not re-register while system location is switched off`() = runServiceTest {
+ // The OS hands out no fixes while location is off, and the request survives the toggle
+ every { deviceInfoHelper.isLocationEnabled() } returns false
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtUptimeMs", -700_000L)
+
+ invokeRecoverStalledStream()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `heartbeat keeps ticking after it recovers a stalled stream`() = runServiceTest {
+ // Recovery cancels the job it runs in and relies on setupLocationUpdates relaunching the
+ // logger; if that stops happening, recovery and the 5-min diagnostics die silently
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtUptimeMs", -700_000L)
+ invokeStartTrackingHeartbeatLogger()
+
+ advanceTimeBy(5 * 60_000L + 1)
+ runCurrent()
+
+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ assertTrue("heartbeat loop must survive its own recovery", getField<Job?>("trackingHeartbeatJob")?.isActive == true)
+ }
+
+ @Test
+ fun `leaves a healthy stream alone`() = runServiceTest {
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtUptimeMs", -10_000L) // 10s since the last fix
+
+ invokeRecoverStalledStream()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `does not re-register while paused in a zone`() = runServiceTest {
+ // A zone pause stops fixes on purpose, and the pause watchdog owns that resume
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("insidePauseZone", true)
+ setField("lastFixAtUptimeMs", -700_000L)
+
+ invokeRecoverStalledStream()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `stall threshold scales with the configured interval`() = runServiceTest {
+ // 30-min interval -> threshold max(10min, 150min), so an 11-min gap is normal, not a stall
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 30 * 60_000L,
+ accuracyThreshold = 50f,
+ filterInaccurateLocations = true,
+ syncIntervalSeconds = 0
+ ))
+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
+ setField("lastFixAtUptimeMs", -700_000L)
+
+ invokeRecoverStalledStream()
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
@Test
fun `handleLocationUpdate while paused rejects a hallucinated outlier instead of fabricating an exit`() = testScope.runTest {
// A teleport-signature fix (huge implied speed, ~0 chip speed) lands outside the radius but
@@ -2366,6 +2475,36 @@ class LocationForegroundServiceTest {
verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
}
+ @Test
+ fun `applyZoneSettingsIfChanged resumes GPS that no hold explains`() {
+ // A restore that dropped a stale motionless hold leaves the flag already false, so there
+ // is no transition to resume on and a lightweight action never runs handleStart
+ val detector = mockk<MotionStateDetector>(relaxed = true)
+ setField("motionDetector", detector)
+ setField("currentZoneGeofence", homeGeofence)
+ setField("isMotionlessPaused", false)
+ setField("locationUpdateCallback", null)
+
+ invokeApplyZoneSettingsIfChanged(homeGeofence)
+
+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `applyZoneSettingsIfChanged leaves a held stream stopped`() {
+ // The state check must not defeat the holds: a motionless hold means GPS is off on purpose
+ val motionlessGeofence = geofence("Home", 52.50, 13.40, 150.0, pauseOnMotionless = true)
+ setField("motionDetector", mockk<MotionStateDetector>(relaxed = true))
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", motionlessGeofence)
+ setField("isMotionlessPaused", true)
+ setField("locationUpdateCallback", null)
+
+ invokeApplyZoneSettingsIfChanged(motionlessGeofence)
+
+ verify(exactly = 0) { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
@Test
fun `applyZoneSettingsIfChanged starts motion detector when pauseOnMotionless toggled on`() {
val detector = mockk<MotionStateDetector>(relaxed = true)
@@ -2461,6 +2600,18 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
+ private fun invokeStartTrackingHeartbeatLogger() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("startTrackingHeartbeatLogger")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
+ private fun invokeRecoverStalledStream() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("recoverStalledStream")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
private fun invokeRunPauseWatchdogTick() {
val method = LocationForegroundService::class.java
.getDeclaredMethod("runPauseWatchdogTick")
diff --git a/fastlane/metadata/android/en-US/changelogs/45.txt b/fastlane/metadata/android/en-US/changelogs/45.txt
index 59eb98e0..5dd3f85a 100644
--- a/fastlane/metadata/android/en-US/changelogs/45.txt
+++ b/fastlane/metadata/android/en-US/changelogs/45.txt
@@ -4,4 +4,5 @@
- Merge adjacent trips from the Trips selection bar when one journey got split up
- Split a trip by tapping the point on the map where the new trip should start
- Trips show an average speed instead of 0 km/h when the points carry no speed, including imported tracks
-- Tracking no longer gets stuck on Pause after a geofence is deleted or its motionless pause is turned off
\ No newline at end of file
+- Tracking no longer gets stuck on Pause after a geofence is deleted or its motionless pause is turned off
+- Tracking restarts itself when the phone stops delivering locations, instead of staying silent until you reinstall