Skip to content

Colota - Android GPS Location tracker

fix(service): keep the diagnostic running through pauses (#602)

Max Dietrich7967cf23a3f0
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 8a85efb4..e43f441c 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
@@ -331,12 +331,13 @@ class LocationForegroundService : Service() {
ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
)
} catch (e: Exception) {
- AppLogger.e(TAG, "Cannot start foreground service - background start restricted", e)
+ AppLogger.e(TAG, "Cannot start foreground service (${deniedStartCause(e)})", e)
stopSelf()
return START_NOT_STICKY
}
if (!isLightweight) {
+ startTrackingHeartbeatLogger()
dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
dbHelper.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "false")
BatteryRecoveryScheduler.cancel(this)
@@ -429,6 +430,7 @@ class LocationForegroundService : Service() {
teardownStep("batteryMonitor") { batteryMonitor.stop() }
teardownStep("conditionMonitor") { conditionMonitor.stop() }
teardownStep("locationUpdates") { stopLocationUpdates() }
+ teardownStep("trackingHeartbeatLogger") { cancelTrackingHeartbeatLogger() }
teardownStep("periodicSync") { syncManager.stopPeriodicSync() }
teardownStep("networkManager") { networkManager.destroy() }
@@ -528,7 +530,6 @@ class LocationForegroundService : Service() {
)
}
- startTrackingHeartbeatLogger()
startPauseWatchdog()
} catch (e: SecurityException) {
AppLogger.e(TAG, "Location permission missing", e)
@@ -539,8 +540,15 @@ class LocationForegroundService : Service() {
}
}
+ /** Matched by name because the class is API 31+ and its IllegalStateException superclass is too broad. */
+ private fun deniedStartCause(e: Exception): String = when {
+ e.javaClass.simpleName == "ForegroundServiceStartNotAllowedException" -> "background start not allowed"
+ e is SecurityException -> "missing foreground-service location permission"
+ else -> e.javaClass.simpleName
+ }
+
private fun stopLocationUpdates() {
- cancelTrackingHeartbeatLogger()
+ // The heartbeat logger outlives the stream; the watchdog only probes while it is live.
stopPauseWatchdog()
locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }
locationUpdateCallback = null
@@ -560,7 +568,8 @@ class LocationForegroundService : Service() {
/** Logs a state snapshot every 5 minutes so silent stalls and pause/stop gaps are visible
* in user-exported logs, and re-registers a stream that has gone quiet while active. */
private fun startTrackingHeartbeatLogger() {
- trackingHeartbeatJob?.cancel()
+ // onStartCommand re-enters often; restarting would reset the interval before it ever fires.
+ if (trackingHeartbeatJob?.isActive == true) return
val scope = serviceScope ?: return
trackingHeartbeatJob = scope.launch {
while (isActive) {
@@ -573,7 +582,7 @@ class LocationForegroundService : Service() {
val doze = (getSystemService(POWER_SERVICE) as? PowerManager)?.isDeviceIdleMode ?: false
AppLogger.i(TAG,
"Heartbeat state=$state, ${sinceLastFix / 1000}s since last fix, " +
- "queue=${dbHelper.getStats().queued}, batt=$battery%, " +
+ "queue=${dbHelper.getQueuedCount()}, batt=$battery%, " +
"profile=${profileManager.getActiveProfileName() ?: "default"}, doze=$doze"
)
} catch (e: Exception) {
@@ -582,7 +591,7 @@ class LocationForegroundService : Service() {
try {
withContext(Dispatchers.Main) { recoverStalledStream() }
} catch (e: CancellationException) {
- throw e // recovery cancels this job on purpose; swallowing it would leave two loops
+ throw e // service teardown; swallowing it would outlive the scope
} catch (e: Exception) {
AppLogger.w(TAG, "Stall recovery failed: ${e.message}")
}
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 c1bed727..a01ea98b 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
@@ -1072,9 +1072,9 @@ class LocationForegroundServiceTest {
}
@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
+ fun `the 5-minute loop is what drives stall recovery`() = runServiceTest {
+ // Nothing else probes a stream that died while active, so if this loop stops calling
+ // recoverStalledStream the stall is never noticed
setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))
setField("lastFixAtUptimeMs", -700_000L)
invokeStartTrackingHeartbeatLogger()
@@ -1083,7 +1083,47 @@ class LocationForegroundServiceTest {
runCurrent()
verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
- assertTrue("heartbeat loop must survive its own recovery", getField<Job?>("trackingHeartbeatJob")?.isActive == true)
+ assertTrue("and it has to keep ticking afterwards", getField<Job?>("trackingHeartbeatJob")?.isActive == true)
+ }
+
+ @Test
+ fun `heartbeat logger survives a pause stopping the stream`() = runServiceTest {
+ // Every pause path goes through stopLocationUpdates, and a pause is a state worth logging
+ invokeStartTrackingHeartbeatLogger()
+
+ invokeStopLocationUpdates()
+
+ assertTrue(
+ "a pause must not silence the diagnostic that explains the pause",
+ getField<Job?>("trackingHeartbeatJob")?.isActive == true
+ )
+ }
+
+ @Test
+ fun `starting the heartbeat logger twice keeps the original loop`() = runServiceTest {
+ // onStartCommand re-enters often; a restart would reset the interval before it ever fires
+ invokeStartTrackingHeartbeatLogger()
+ val first = getField<Job?>("trackingHeartbeatJob")
+
+ invokeStartTrackingHeartbeatLogger()
+
+ assertSame("second call must be a no-op", first, getField<Job?>("trackingHeartbeatJob"))
+ assertTrue(first?.isActive == true)
+ }
+
+ /** Stands in for the API 31+ framework class, which deniedStartCause matches by simple name. */
+ private class ForegroundServiceStartNotAllowedException : IllegalStateException()
+
+ @Test
+ fun `a denied start names which failure it was`() = runServiceTest {
+ // A start refused at boot reaches no one, so the log is the only place the two causes can
+ // still be told apart afterwards
+ assertEquals(
+ "background start not allowed",
+ invokeDeniedStartCause(ForegroundServiceStartNotAllowedException())
+ )
+ assertTrue(invokeDeniedStartCause(SecurityException("nope")).contains("permission"))
+ assertEquals("IllegalArgumentException", invokeDeniedStartCause(IllegalArgumentException("odd")))
}
@Test
@@ -2606,6 +2646,19 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
+ private fun invokeStopLocationUpdates() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("stopLocationUpdates")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
+ private fun invokeDeniedStartCause(e: Exception): String {
+ val method = LocationForegroundService::class.java
+ .getDeclaredMethod("deniedStartCause", Exception::class.java)
+ method.isAccessible = true
+ return method.invoke(service, e) as String
+ }
+
private fun invokeRecoverStalledStream() {
val method = LocationForegroundService::class.java.getDeclaredMethod("recoverStalledStream")
method.isAccessible = true