Colota - Android GPS Location tracker
fix(service): post the resume notification when a background start is refused with location services off (#896)
Max Dietrichb30cb97bf38b
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex c6363a36..0fec5e38 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -170,9 +170,9 @@ Handles all notification logic for the tracking service:- Text is the sending state ("All sent", "12 queued · last sync 3 min ago", "Offline mode"), after "Stationary", "Not recording" or how a pause resumes where one applies. `NotificationHelper.StatusInput` has no coordinate, zone or profile field and `statusInput()` in the service is its only builder- `Notification.when` is the last fix received, so the header age updates without a post. An update posts when the title, the text or the fix minute changes. A state change always posts- Both notifications are `VISIBILITY_PUBLIC`, since the text holds nothing private-- Small icon `drawable/ic_notification`: the launcher's monochrome pin and inner arc at 24 dp, without the outer arc and with the stroke doubled. `setColor(ICON_COLOR)`, the launcher background, colors the circle Android 12 and later draw behind it. `BatteryRecoveryWorker` uses the same icon and color. The stopped notification keeps `ic_lock_power_off` so the status bar icon changes when tracking ends, and backup and auto-export keep `ic_menu_save`+- Small icon `drawable/ic_notification`: the launcher's monochrome pin and inner arc at 24 dp, without the outer arc and with the stroke doubled. `setColor(ICON_COLOR)`, the launcher background, colors the circle Android 12 and later draw behind it. `BatteryRecoveryWorker` and the stopped notification use the same icon and color, so the status bar shows one Colota icon whether tracking runs or has stopped; backup and auto-export keep `ic_menu_save`.- Deduplication to avoid unnecessary notification redraws-- Stopped notification, posted on a deliberate stop and by the tracking watchdog when Android refuses a background restart, in which case tapping it opens the app so the reconciler can resume. Two channels back it. `location_service_channel` at `IMPORTANCE_LOW` carries the ongoing status and any stop the user asked for; `tracking_stopped_channel` at `IMPORTANCE_DEFAULT` carries the ones they did not, so a killed service is audible instead of sitting silently under the ongoing notification. `buildStoppedNotification` defaults to the silent channel and callers opt in+- Stopped notification, posted on a deliberate stop, by the tracking watchdog when Android refuses a background restart, and by the service itself when Android refuses the location foreground type because location services are off; in both refusal cases tapping it opens the app so the reconciler can resume. Two channels back it. `location_service_channel` at `IMPORTANCE_LOW` carries the ongoing status and any stop the user asked for; `tracking_stopped_channel` at `IMPORTANCE_DEFAULT` carries the ones they did not, so a killed service is audible instead of sitting silently under the ongoing notification. `buildStoppedNotification` defaults to the silent channel and callers opt in### DatabaseHelper@@ -278,7 +278,7 @@ For backups, two `internal` methods support the export/import flow without expos| `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 |-| `TrackingWatchdogScheduler` | Arms a 15min `setAndAllowWhileIdle` alarm for as long as tracking is wanted, re-armed by each tick and cancelled on stop. 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 |+| `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 || `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.mdindex a311ebfa..37a3d7a6 100644--- a/apps/docs/docs/guides/troubleshooting.md+++ b/apps/docs/docs/guides/troubleshooting.md@@ -22,6 +22,7 @@ sidebar_position: 4- **Xiaomi, Huawei, Oppo, Vivo, OnePlus**: allow Autostart for Colota in the phone's own security or battery app- Disable battery optimization for Colota (**Settings > Apps > Colota > Battery > Unrestricted**)- Open the app once if you have not used it for months. Android resets permissions for unused apps+- **Location services were off during the reboot**: Android 14 and newer block the automatic start until location services are on. Colota posts a "Tracking stopped" notification instead. Tap it to resume right away, or turn location services on and tracking resumes by itself within about 10 minutes## Tracking stopped on low battery and didn't resumediff --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 2927affe..8d29b076 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@@ -346,10 +346,22 @@ class LocationForegroundService : Service() {ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)} catch (e: Exception) {- AppLogger.e(TAG, "Cannot start foreground service (${deniedStartCause(e)})", e)+ val locationOff = e is SecurityException && !deviceInfoHelper.isLocationEnabled()+ AppLogger.e(TAG, "Cannot start foreground service (${if (locationOff) "location services are off" else deniedStartCause(e)})", e)// The user's intent survives a denied start; the watchdog retries it out of process.// An explicit start is intent too, even before the bridge's async flag write lands.- if (shouldBeTracking || !isLightweight) TrackingWatchdogScheduler.schedule(this)+ if (shouldBeTracking || !isLightweight) {+ if (locationOff) {+ // Nothing wakes a dead app when Location comes back on, so the user is told and the retry is short.+ TrackingWatchdogScheduler.scheduleLocationOffRetry(this)+ notificationManager.notify(+ NotificationHelper.STOPPED_NOTIFICATION_ID,+ notificationHelper.buildStoppedNotification(NotificationHelper.STOP_REASON_LOCATION_OFF, unexpected = true)+ )+ } else {+ TrackingWatchdogScheduler.schedule(this)+ }+ }stopSelf()return START_NOT_STICKY}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.ktindex a7d9c4c0..acebc3b1 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt@@ -50,6 +50,8 @@ class NotificationHelper(const val NOTIFICATION_ID = 1const val STOPPED_NOTIFICATION_ID = 2const val STOP_REASON_BATTERY = "Battery fell below 5% · resumes when charging"+ const val STOP_REASON_LOCATION_OFF =+ "Location services are off · tap to resume now, or it resumes by itself within 10 min of turning them on"/** ic_launcher_background, copied because unit tests run without app resources. */const val ICON_COLOR = 0xFF0D9387.toInt()}@@ -121,7 +123,8 @@ class NotificationHelper(.setContentTitle(collapsedTitle("Tracking stopped")).setContentText(collapsedText("Tracking stopped", reason)).setStyle(NotificationCompat.BigTextStyle().setBigContentTitle("Tracking stopped").bigText(reason))- .setSmallIcon(android.R.drawable.ic_lock_power_off)+ .setSmallIcon(R.drawable.ic_notification)+ .setColor(ICON_COLOR).setOngoing(false).setAutoCancel(true)// Silences the watchdog's 15-minute re-post while this one still shows. Dismissing itdiff --git a/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogScheduler.ktindex 61e10ddb..d64d3a02 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogScheduler.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogScheduler.kt@@ -19,6 +19,9 @@ object TrackingWatchdogScheduler {/** Above the ~9min Doze floor for allow-while-idle, and matches the default heartbeat. */const val INTERVAL_MS = 15 * 60_000L+ /** Nothing wakes the app when Location comes back on; Doze still batches this to ~9 min. */+ const val LOCATION_OFF_RETRY_MS = 5 * 60_000L+private val alarm = AlarmScheduler(tag = "TrackingWatchdog",requestCode = 9303,@@ -27,5 +30,7 @@ object TrackingWatchdogScheduler {fun schedule(context: Context) = alarm.schedule(context, INTERVAL_MS)+ fun scheduleLocationOffRetry(context: Context) = alarm.schedule(context, LOCATION_OFF_RETRY_MS)+fun cancel(context: Context) = alarm.cancel(context)}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 72662e13..c1b28fb2 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@@ -113,6 +113,7 @@ class LocationForegroundServiceTest {mockkObject(GeofenceHeartbeatScheduler)mockkObject(TrackingWatchdogScheduler)every { TrackingWatchdogScheduler.schedule(any()) } just Runs+ every { TrackingWatchdogScheduler.scheduleLocationOffRetry(any()) } just Runsevery { TrackingWatchdogScheduler.cancel(any()) } just Runsevery { GeofenceHeartbeatScheduler.schedule(any(), any()) } just Runsevery { GeofenceHeartbeatScheduler.cancel(any()) } just Runs@@ -3434,6 +3435,13 @@ class LocationForegroundServiceTest {every { dbHelper.getAllSettings() } returns mapOf(SettingsKeys.TRACKING_ENABLED to "false")}+ /** The stubbed android.jar reports SDK 0, so ServiceCompat calls the two-argument overload. */+ private fun refuseStartForeground() {+ val refused = SecurityException("Starting FGS with type location")+ every { service.startForeground(any<Int>(), any()) } throws refused+ every { service.startForeground(any<Int>(), any(), any<Int>()) } throws refused+ }+private fun intentFor(action: String?): Intent = mockk(relaxed = true) {every { [email protected] } returns actionevery { getStringExtra(any()) } returns null@@ -3517,6 +3525,40 @@ class LocationForegroundServiceTest {verify { service.stopSelf() }}+ /** Android refuses the location type to a boot start while Location is off; without this the user sees nothing. */+ @Test+ fun `a start refused while location services are off posts the resume notification and retries sooner`() = runServiceTest {+ makeCold()+ every { deviceInfoHelper.isLocationEnabled() } returns false+ refuseStartForeground()+ val stopped = mockk<android.app.Notification>(relaxed = true)+ every { notificationHelper.buildStoppedNotification(NotificationHelper.STOP_REASON_LOCATION_OFF, true) } returns stopped++ val result = service.onStartCommand(intentFor(null), 0, 1)+ advanceUntilIdle()++ assertEquals(android.app.Service.START_NOT_STICKY, result)+ verify { androidNotificationManager.notify(NotificationHelper.STOPPED_NOTIFICATION_ID, stopped) }+ verify { TrackingWatchdogScheduler.scheduleLocationOffRetry(any()) }+ verify(exactly = 0) { TrackingWatchdogScheduler.schedule(any()) }+ verify { service.stopSelf() }+ }++ /** Other refusals are not the user's to fix, so only the watchdog handles them. */+ @Test+ fun `a start refused with location services on posts no notification`() = runServiceTest {+ makeCold()+ refuseStartForeground()++ service.onStartCommand(intentFor(null), 0, 1)+ advanceUntilIdle()++ verify(exactly = 0) { androidNotificationManager.notify(NotificationHelper.STOPPED_NOTIFICATION_ID, any()) }+ verify { TrackingWatchdogScheduler.schedule(any()) }+ verify(exactly = 0) { TrackingWatchdogScheduler.scheduleLocationOffRetry(any()) }+ verify { service.stopSelf() }+ }+@Testfun `a manual flush while tracking leaves the service running`() = runServiceTest {makeCold()diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.ktindex 1796ce62..3787755c 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt@@ -159,6 +159,14 @@ class NotificationHelperTest {assertEquals(0xFF0D9387.toInt(), posted().color)}+ @Test+ fun `the stopped notification carries the same icon and color`() {+ val n = helper.buildStoppedNotification("killed", unexpected = true)++ assertEquals(R.drawable.ic_notification, n.smallIcon.resId)+ assertEquals(0xFF0D9387.toInt(), n.color)+ }+@Testfun `the header time is the last fix received`() {val s = input(hasFix = true, lastFixMs = FIX)diff --git a/fastlane/metadata/android/en-US/changelogs/51.txt b/fastlane/metadata/android/en-US/changelogs/51.txtindex 71a76a80..882ff5d1 100644--- a/fastlane/metadata/android/en-US/changelogs/51.txt+++ b/fastlane/metadata/android/en-US/changelogs/51.txt@@ -2,3 +2,4 @@- Setup links show the full server address with its host on its own line, name the server they replace and are rejected as a whole when the address hides its host- Placing a geofence shows where you are and the locate button puts the zone there- A tracking profile's sync interval takes effect as soon as the profile switches+- Tracking that cannot restart after a reboot because location services are off shows a tap-to-resume notification and resumes by itself within about 10 minutes of turning them on