Colota - Android GPS Location tracker
fix(service): restart a tracking service that was created but never started (#982)
Max Dietrichfd5b7aa208eb
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 9e2757a9..bb646dc8 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -163,7 +163,7 @@ An Android foreground service that runs continuously for GPS tracking. Manages:**Alarms go through a receiver, not the service.** Each scheduler targets a `BroadcastReceiver` that then starts the service. That keeps the PendingIntent a plain explicit broadcast, and the foreground-service start runs inside the alarm's temporary allowlist window.-**Intent vs liveness.** The `tracking_enabled` setting records that the user wants tracking and deliberately survives process death and reboot. Whether a service exists right now is `LocationForegroundService.isRunning`. Anything asking "is tracking alive" must read `isRunning`, because a service the system killed leaves the flag true. Recovery is layered: the app reconciles the two whenever it reaches the foreground, and `TrackingWatchdogScheduler` covers the window while the app stays closed. Reconciling can also drop the intent rather than honour it: a revoked location permission means no service can be started again, so the foreground reconciler clears the flag and the watchdog stops re-arming itself.+**Intent vs liveness.** The `tracking_enabled` setting records that the user wants tracking and deliberately survives process death and reboot. Whether a service exists right now is `LocationForegroundService.isRunning`; whether it was started is `isStarted`, set just before `onStartCommand` dispatches its action. Android can create the service and never deliver its start, and that instance has no location stream and no sync: on AOSP a restart after the app's task was removed calls `onTaskRemoved` instead, which only logs `Task removed (started=false)`. The watchdog and the app's revive read `isStarted`, never the setting, because a service the system killed leaves the setting true. Recovery is layered: the app reconciles the two whenever it reaches the foreground, and `TrackingWatchdogScheduler` covers the window while the app stays closed. Reconciling can also drop the intent rather than honour it: a revoked location permission means no service can be started again, so the foreground reconciler clears the flag and the watchdog stops re-arming itself.### NotificationHelper@@ -286,7 +286,7 @@ For backups, two `internal` methods support the export/import flow without expos| `LocationBootReceiver` | Auto-restarts tracking after device reboot || `AlarmScheduler` | Shared one-shot wake-up alarm used by the geofence heartbeat, the stationary heartbeat and the tracking watchdog. `setAndAllowWhileIdle` fires through Doze without `SCHEDULE_EXACT_ALARM`, at the cost of being inexact, so every interval built on it is a minimum and not a schedule. Floors the delay at 60s, and each alarm needs its own request code. Whoever handles a tick re-arms the next one || `GeofenceHeartbeatScheduler` / `GeofenceHeartbeatReceiver` | Wakes the service for the zone heartbeat while paused in a geofence. Replaced a coroutine delay, which stopped counting while the phone slept |-| `TrackingWatchdogReceiver` | Fired by `TrackingWatchdogScheduler` - restarts the service when the user still wants tracking but none is running. Where Android refuses a background start it posts a resume notification instead, and records when notifications are denied too |+| `TrackingWatchdogReceiver` | Fired by `TrackingWatchdogScheduler` - restarts the service when the user still wants tracking but none is running, or the one that exists was never started. Where Android refuses a background start it posts a resume notification instead, and records when notifications are denied too || `TrackingWatchdogScheduler` | Arms a 15min `setAndAllowWhileIdle` alarm for as long as tracking is wanted, re-armed by each tick and cancelled on stop; a start refused because location services are off re-arms it at 5min instead. Distinct from the in-service pause watchdog, which dies with the service it would have to watch. Doze defers these alarms, so the interval is a minimum || `MotionStateDetector` / `RawSensorMotionDetector` | Single detector behind a `MotionState { STATIONARY, MOVING }` interface. Backed by 30s-batched accelerometer variance (hysteresis: > 0.30 m/s² for 3s -> MOVING; < 0.15 m/s² for the configured per-zone dwell -> STATIONARY) and parallel `TYPE_SIGNIFICANT_MOTION` as a fast-path for sharp events. Fans out to both motionless-pause and stationary-profile exit consumers via one callback site in `LocationForegroundService.onMotionStateChange`. || `DeviceInfoHelper` | Device metadata and battery status with caching |@@ -411,7 +411,7 @@ Supporting utilities in `mapUtils.ts`:| Hook | Purpose || --- | --- |-| `useLocationTracking` | Manages the foreground service lifecycle, native event subscriptions, and location state. On app foreground it reconciles the user's intent against real service liveness and restarts a service that died |+| `useLocationTracking` | Manages the foreground service lifecycle, native event subscriptions and location state. On app foreground it reconciles the user's intent against real service liveness and restarts a service that died or was never started || `useTheme` | Provides theme colors, mode, and toggle from ThemeProvider context || `useAutoSave` | Debounced auto-save pattern for settings screens || `useTimeout` | Managed timeout with automatic cleanup on unmount |diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.mdindex 37a3d7a6..bd6bf5fa 100644--- a/apps/docs/docs/guides/troubleshooting.md+++ b/apps/docs/docs/guides/troubleshooting.md@@ -13,6 +13,7 @@ sidebar_position: 4- If the notification disappeared while the app still shows tracking on, Android killed the service. Opening the app restarts it. With battery set to **Unrestricted** it also restarts on its own, usually within 15 to 30 minutes- When Colota cannot restart itself it posts a **Tracking stopped** notification instead, and tapping that resumes tracking. It has its own notification channel, so if you never see it, check that **Tracking stopped** is enabled in Android's notification settings for Colota- The time in the notification header is the last position fix Colota received. It keeps counting while a pause keeps GPS off. While you move, it only grows if location updates have stopped+- If the notification stays but its time keeps counting while you move, Android may have brought the service back without starting it. Opening the app starts it. With battery set to **Unrestricted** it also starts on its own, usually within 15 to 30 minutes## Tracking doesn't start after rebootdiff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex 83a7f6dd..544c5b49 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -323,7 +323,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :// JS logging never reaches the exported log, so record here that this start is a// recovery - otherwise a report of "it stopped recording" shows the restart but// never says the service had died while the user still wanted tracking.- if (!LocationForegroundService.isRunning &&+ if (!LocationForegroundService.isStarted &&dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true") {AppLogger.w(TAG, "Starting a service that died while tracking was on")@@ -907,10 +907,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.resolve(deviceInfo.isLocationEnabled())}- /** Whether a service instance is alive. TRACKING_ENABLED is the user's intent, not this. */+ /** Whether a started service instance is alive. TRACKING_ENABLED is the user's intent, not this. */@ReactMethodfun isServiceRunning(promise: Promise) {- promise.resolve(LocationForegroundService.isRunning)+ promise.resolve(LocationForegroundService.isStarted)}@ReactMethoddiff --git a/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt b/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.ktindex 82fd69c9..9ee4c505 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/SettingsKeys.kt@@ -8,7 +8,7 @@ package com.Colota.data/** Runtime state keys persisted via DatabaseHelper.saveSetting/getSetting. */object SettingsKeys {/** The user's intent to track, which outlives the process. Liveness is- * [com.Colota.service.LocationForegroundService.isRunning] - never this. */+ * [com.Colota.service.LocationForegroundService.isStarted] - never this. */const val TRACKING_ENABLED = "tracking_enabled"const val PAUSE_ZONE_NAME = "pause_zone_name"const val PAUSE_ZONE_WIFI_ACTIVE = "pause_zone_wifi_active"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.ktindex 25313daf..644c9af7 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@@ -137,6 +137,12 @@ class LocationForegroundService : Service() {var isRunning: Boolean = falseprivate set+ /** True from the action dispatch in onStartCommand until onDestroy. */+ @Volatile+ @JvmStatic+ var isStarted: Boolean = false+ private set+/** Multiplier applied to the tracking interval for the geofence entry delay. */private const val ENTRY_DELAY_MULTIPLIER = 3.5/** Debounce before resuming GPS after unmetered network is lost (ms). */@@ -388,6 +394,8 @@ class LocationForegroundService : Service() {batteryMonitor.start()}+ isStarted = true+when (action) {ACTION_REFRESH_NOTIFICATION -> handleRefreshNotification()ACTION_RECHECK_ZONE -> handleZoneRecheckAction()@@ -484,6 +492,7 @@ class LocationForegroundService : Service() {serviceScope = nullnotificationManager.cancel(NotificationHelper.NOTIFICATION_ID)+ isStarted = falseisRunning = falsesuper.onDestroy()}@@ -501,6 +510,11 @@ class LocationForegroundService : Service() {override fun onBind(intent: Intent?): IBinder? = null+ override fun onTaskRemoved(rootIntent: Intent?) {+ AppLogger.d(TAG, "Task removed (started=$isStarted)")+ super.onTaskRemoved(rootIntent)+ }+private fun setupLocationUpdates(skipEntryDelay: Boolean = false) {if (isWifiPaused || isMotionlessPaused) return // GPS intentionally stopped by a zone pause holddiff --git a/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.ktindex 18395a73..d52cab48 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt@@ -36,7 +36,7 @@ class TrackingWatchdogReceiver : BroadcastReceiver() {return}- if (LocationForegroundService.isRunning) {+ if (LocationForegroundService.isStarted) {AppLogger.d(TAG, "Service is running")TrackingWatchdogScheduler.schedule(context)return@@ -51,7 +51,11 @@ class TrackingWatchdogReceiver : BroadcastReceiver() {return}- AppLogger.w(TAG, "Tracking wanted but the service is not running - restarting")+ if (LocationForegroundService.isRunning) {+ AppLogger.w(TAG, "Service was created but never started - starting it")+ } else {+ AppLogger.w(TAG, "Tracking wanted but the service is not running - restarting")+ }try {LocationForegroundService.startTracking(context, dbHelper, "Restarted by watchdog")} catch (e: Exception) {diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktindex b3b63b97..2d1dac61 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -714,6 +714,7 @@ class LocationServiceModuleTest {fun `startService records that it is reviving a service which died while tracking was on`() {val (module, dbHelper) = createModuleWithDeps()every { LocationForegroundService.isRunning } returns false+ every { LocationForegroundService.isStarted } returns falseevery { dbHelper.getSetting("tracking_enabled", "false") } returns "true"mockkConstructor(Intent::class)try {@@ -725,10 +726,42 @@ class LocationServiceModuleTest {}}+ @Test+ fun `startService records that it is reviving a service which was created but never started`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { LocationForegroundService.isRunning } returns true+ every { LocationForegroundService.isStarted } returns false+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"+ mockkConstructor(Intent::class)+ try {+ module.startService(JavaOnlyMap(), mockk(relaxed = true))++ verify { AppLogger.w(any(), "Starting a service that died while tracking was on") }+ } finally {+ unmockkConstructor(Intent::class)+ }+ }++ @Test+ fun `startService stays quiet when restarting a started service`() {+ val (module, dbHelper) = createModuleWithDeps()+ every { LocationForegroundService.isStarted } returns true+ every { dbHelper.getSetting("tracking_enabled", "false") } returns "true"+ mockkConstructor(Intent::class)+ try {+ module.startService(JavaOnlyMap(), mockk(relaxed = true))++ verify(exactly = 0) { AppLogger.w(any(), "Starting a service that died while tracking was on") }+ } finally {+ unmockkConstructor(Intent::class)+ }+ }+@Testfun `startService stays quiet on an ordinary user start`() {val (module, dbHelper) = createModuleWithDeps()every { LocationForegroundService.isRunning } returns false+ every { LocationForegroundService.isStarted } returns falseevery { dbHelper.getSetting("tracking_enabled", "false") } returns "false"mockkConstructor(Intent::class)try {@@ -745,16 +778,29 @@ class LocationServiceModuleTest {// ========================================================================@Test- fun `isServiceRunning resolves the service's own liveness flag`() {+ fun `isServiceRunning resolves true for a started service`() {val (module, _) = createModuleWithDeps()val promise = mockk<com.facebook.react.bridge.Promise>(relaxed = true)- every { LocationForegroundService.isRunning } returns true+ every { LocationForegroundService.isStarted } returns truemodule.isServiceRunning(promise)verify { promise.resolve(true) }}+ /** reviveIfDead restarts only a service this reports as down. */+ @Test+ fun `isServiceRunning resolves false for a service that was created but never started`() {+ val (module, _) = createModuleWithDeps()+ val promise = mockk<com.facebook.react.bridge.Promise>(relaxed = true)+ every { LocationForegroundService.isRunning } returns true+ every { LocationForegroundService.isStarted } returns false++ module.isServiceRunning(promise)++ verify { promise.resolve(false) }+ }+// ========================================================================// Module name// ========================================================================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.ktindex 92a72652..f4ef2de6 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@@ -144,6 +144,8 @@ class LocationForegroundServiceTest {unmockkObject(GeofenceHeartbeatScheduler)unmockkObject(TrackingWatchdogScheduler)unmockkStatic(android.os.Looper::class)+ // A process-wide static: a start in one test would leave it true for the next.+ LocationForegroundService::class.java.getDeclaredField("isStarted").apply { isAccessible = true }.setBoolean(null, false)}private fun injectDependencies() {@@ -3619,6 +3621,52 @@ class LocationForegroundServiceTest {verify { notificationHelper.buildForegroundNotification(match { it.queuedCount == 7 }) }}+ @Test+ fun `a start marks the instance started`() = runServiceTest {+ makeCold()+ assertFalse(LocationForegroundService.isStarted)++ service.onStartCommand(intentFor(null), 0, 1)+ advanceUntilIdle()++ assertTrue(LocationForegroundService.isStarted)+ }++ @Test+ fun `onDestroy clears the started flag`() = runServiceTest {+ makeCold()+ service.onStartCommand(intentFor(null), 0, 1)+ advanceUntilIdle()++ invokeOnDestroy()++ assertFalse(LocationForegroundService.isStarted)+ }++ @Test+ fun `a refused start leaves the instance not started`() = runServiceTest {+ makeCold()+ refuseStartForeground()++ service.onStartCommand(intentFor(null), 0, 1)+ advanceUntilIdle()++ assertFalse(LocationForegroundService.isStarted)+ }++ @Test+ fun `onTaskRemoved logs whether the instance was ever started`() = runServiceTest {+ service.onTaskRemoved(null)+ verify { AppLogger.d(any(), "Task removed (started=false)") }++ makeCold()+ service.onStartCommand(intentFor(null), 0, 1)+ advanceUntilIdle()+ service.onTaskRemoved(null)++ verify { AppLogger.d(any(), "Task removed (started=true)") }+ }+/** Without this, the tracking notification sits over a service that records nothing. */@Testfun `a lightweight wake on a cold service starts tracking in full`() = runServiceTest {diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/TrackingWatchdogReceiverTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/TrackingWatchdogReceiverTest.ktindex 885a34ae..6d83a0dd 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/TrackingWatchdogReceiverTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/TrackingWatchdogReceiverTest.kt@@ -87,6 +87,7 @@ class TrackingWatchdogReceiverTest {mockkObject(LocationForegroundService.Companion)try {every { LocationForegroundService.isRunning } returns true+ every { LocationForegroundService.isStarted } returns truefire()@@ -97,6 +98,28 @@ class TrackingWatchdogReceiverTest {}}+ /** An instance Android created and never started has no stream and no sync. */+ @Test+ fun `starts a service that was created but never started`() {+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")++ mockkObject(LocationForegroundService.Companion)+ try {+ every { LocationForegroundService.isRunning } returns true+ every { LocationForegroundService.isStarted } returns false++ fire()++ val started = shadowOf(app).nextStartedService+ assertNotNull("An instance that never started records nothing", started)+ assertEquals(LocationForegroundService::class.java.name, started.component?.className)+ verify { AppLogger.w(any(), "Service was created but never started - starting it") }+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)+ } finally {+ unmockkObject(LocationForegroundService.Companion)+ }+ }+@Testfun `disarms itself once the user stops tracking`() {db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")@@ -118,6 +141,7 @@ class TrackingWatchdogReceiverTest {mockkObject(LocationForegroundService.Companion)try {every { LocationForegroundService.isRunning } returns false+ every { LocationForegroundService.isStarted } returns falseevery {LocationForegroundService.startTracking(any(), any(), any())} throws IllegalStateException("FGS start not allowed from background")@@ -144,6 +168,7 @@ class TrackingWatchdogReceiverTest {mockkObject(LocationForegroundService.Companion)try {every { LocationForegroundService.isRunning } returns false+ every { LocationForegroundService.isStarted } returns falseevery {LocationForegroundService.startTracking(any(), any(), any())} throws IllegalStateException("FGS start not allowed from background")diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.tsindex 7594606b..458d3395 100644--- a/apps/mobile/src/hooks/useLocationTracking.ts+++ b/apps/mobile/src/hooks/useLocationTracking.ts@@ -256,7 +256,7 @@ export function useLocationTracking(settings: Settings, settingsHydrated: boolea)/**- * Restarts the service when the user wants tracking but no service is alive.+ * Restarts the service when the user wants tracking but no started service is alive.** Deliberately skips ensurePermissions: the disclosure is already gated on the location* grants, but the notification request and the battery-exemption dialog are not, sodiff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex fd2f9607..d03fbd3c 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -125,7 +125,7 @@ class NativeLocationService {}/**- * Whether a native service instance is alive right now.+ * Whether a started native service instance is alive right now.* Null means the answer is unknown - callers must not read that as "dead".*/static async isServiceRunning(): Promise<boolean | null> {diff --git a/fastlane/metadata/android/en-US/changelogs/53.txt b/fastlane/metadata/android/en-US/changelogs/53.txtindex 70054721..d0ece16d 100644--- a/fastlane/metadata/android/en-US/changelogs/53.txt+++ b/fastlane/metadata/android/en-US/changelogs/53.txt@@ -2,3 +2,4 @@- Less memory used when opening a day with many points and when sending a large upload backlog- Fixed a trip's average speed and its speed and elevation charts being skewed towards stretches recorded with more points- Positioning accuracy setting in Tracking & sync: High accuracy (default) or Lower accuracy to save battery+- Fixed tracking recording nothing for hours after Android recreated it