Skip to content

Colota - Android GPS Location tracker

feat(service): restart tracking the phone killed while the app was closed

Max Dietrichaff081511687
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index 7f18a083..eae92466 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -132,6 +132,12 @@
android:enabled="true"
android:exported="false" />
+ <!-- Tracking liveness watchdog alarm receiver -->
+ <receiver
+ android:name=".service.TrackingWatchdogReceiver"
+ android:enabled="true"
+ android:exported="false" />
+
<!-- Tracking control receiver (Tasker / automation) -->
<receiver
android:name=".triggers.TrackingControlReceiver"
diff --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.kt
index e59e9fc8..8990b846 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
@@ -19,6 +19,7 @@ import com.Colota.service.LocationForegroundService
import com.Colota.data.SettingsKeys
import com.Colota.service.ProfileConstants
import com.Colota.service.ServiceConfig
+import com.Colota.service.TrackingWatchdogScheduler
import com.Colota.service.getDoubleOrNull
import com.Colota.service.getIntOrNull
import com.Colota.service.getStringOrNull
@@ -330,6 +331,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
// Before the stop, not after: a liveness check racing an async write would see the user's
// intent still true with the service already gone, and restart what they just turned off.
dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+ TrackingWatchdogScheduler.cancel(reactApplicationContext)
val intent = Intent(reactApplicationContext, LocationForegroundService::class.java)
reactApplicationContext.stopService(intent)
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 c764e396..598bb54a 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
@@ -337,6 +337,9 @@ class LocationForegroundService : Service() {
)
} catch (e: Exception) {
AppLogger.e(TAG, "Cannot start foreground service (${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)
stopSelf()
return START_NOT_STICKY
}
@@ -346,6 +349,7 @@ class LocationForegroundService : Service() {
dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
dbHelper.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "false")
BatteryRecoveryScheduler.cancel(this)
+ TrackingWatchdogScheduler.schedule(this)
batteryMonitor.start()
}
@@ -1433,6 +1437,7 @@ class LocationForegroundService : Service() {
dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
dbHelper.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, if (stoppedByBattery) "true" else "false")
if (stoppedByBattery) BatteryRecoveryScheduler.schedule(this)
+ TrackingWatchdogScheduler.cancel(this)
dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_NAME, "")
dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_WIFI_ACTIVE, "false")
dbHelper.saveSetting(SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE, "false")
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.kt
index 8d47acc0..df2189bc 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
@@ -70,12 +70,23 @@ class NotificationHelper(
if (activeProfileName != null) "Colota \u00b7 $activeProfileName" else "Colota Tracking"
fun buildStoppedNotification(reason: String): Notification {
+ // Opening the app is the recovery path when the watchdog cannot restart the service
+ // itself, so this notification has to be tappable.
+ val pendingIntent = PendingIntent.getActivity(
+ context,
+ 0,
+ Intent(context, MainActivity::class.java),
+ PendingIntent.FLAG_IMMUTABLE
+ )
+
return NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Colota: Stopped")
.setContentText(reason)
.setSmallIcon(android.R.drawable.ic_lock_power_off)
.setOngoing(false)
.setAutoCancel(true)
+ .setOnlyAlertOnce(true)
+ .setContentIntent(pendingIntent)
.build()
}
diff --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.kt
new file mode 100644
index 00000000..b18f573f
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt
@@ -0,0 +1,89 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.Manifest
+import android.app.NotificationManager
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.SettingsKeys
+import com.Colota.util.AppLogger
+
+/**
+ * Periodic check that the service the user asked for is actually alive.
+ *
+ * A killed service leaves no in-process guard behind, so this runs out of process. The alarm
+ * grants the power allowlist but not the foreground-service background-start exemption, so the
+ * direct restart only succeeds when the app is exempt from battery optimisation. Otherwise the
+ * user gets a notification that recovers tracking when they tap it.
+ */
+class TrackingWatchdogReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ try {
+ val dbHelper = DatabaseHelper.getInstance(context)
+ val wanted = dbHelper.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
+ if (!wanted) {
+ AppLogger.d(TAG, "Tracking not wanted - watchdog disarmed")
+ return
+ }
+
+ if (LocationForegroundService.isRunning) {
+ AppLogger.d(TAG, "Service is running")
+ TrackingWatchdogScheduler.schedule(context)
+ return
+ }
+
+ val granted = ContextCompat.checkSelfPermission(
+ context,
+ Manifest.permission.ACCESS_FINE_LOCATION
+ ) == PackageManager.PERMISSION_GRANTED
+ if (!granted) {
+ AppLogger.w(TAG, "Service is down but location permission is missing - watchdog disarmed")
+ return
+ }
+
+ AppLogger.w(TAG, "Tracking wanted but the service is not running - restarting")
+ try {
+ LocationForegroundService.startTracking(context, dbHelper, "Restarted by watchdog")
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Watchdog restart failed (${e.javaClass.simpleName})", e)
+ // Tracking can run with notifications denied, so the tap-to-resume fallback
+ // is not always available. Say so rather than assume the user was told.
+ if (NotificationManagerCompat.from(context).areNotificationsEnabled()) {
+ notifyTapToResume(context)
+ } else {
+ AppLogger.w(TAG, "Cannot prompt to resume either - notifications are denied")
+ }
+ }
+ TrackingWatchdogScheduler.schedule(context)
+ } catch (e: Exception) {
+ // A tick can land mid-restore, when the database is deliberately gated.
+ AppLogger.e(TAG, "Watchdog tick failed", e)
+ }
+ }
+
+ private fun notifyTapToResume(context: Context) {
+ val notificationManager =
+ context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ NotificationHelper(context, notificationManager).let {
+ it.createChannel()
+ notificationManager.notify(
+ NotificationHelper.STOPPED_NOTIFICATION_ID,
+ it.buildStoppedNotification("Tracking service was killed - tap to resume")
+ )
+ }
+ }
+
+ companion object {
+ private const val TAG = "TrackingWatchdog"
+ }
+}
diff --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.kt
new file mode 100644
index 00000000..61e10ddb
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogScheduler.kt
@@ -0,0 +1,31 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.Context
+import com.Colota.util.AlarmScheduler
+
+/**
+ * Restarts tracking the system killed while the app was closed. Distinct from the in-service
+ * pause watchdog, which lives on the GPS stream and dies with the service it would have to watch.
+ *
+ * Armed for as long as the user wants tracking, and re-armed by each tick.
+ */
+object TrackingWatchdogScheduler {
+
+ /** Above the ~9min Doze floor for allow-while-idle, and matches the default heartbeat. */
+ const val INTERVAL_MS = 15 * 60_000L
+
+ private val alarm = AlarmScheduler(
+ tag = "TrackingWatchdog",
+ requestCode = 9303,
+ receiver = TrackingWatchdogReceiver::class.java
+ )
+
+ fun schedule(context: Context) = alarm.schedule(context, INTERVAL_MS)
+
+ fun cancel(context: Context) = alarm.cancel(context)
+}
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.kt
index 56f42072..7507e6b7 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
@@ -11,6 +11,7 @@ import com.Colota.data.DatabaseHelper
import com.Colota.data.GeofenceHelper
import com.Colota.data.ProfileHelper
import com.Colota.service.LocationForegroundService
+import com.Colota.service.TrackingWatchdogScheduler
import com.Colota.util.AppLogger
import com.Colota.util.DeviceInfoHelper
import com.facebook.react.bridge.Arguments
@@ -58,6 +59,12 @@ class LocationServiceModuleTest {
mockkObject(LocationForegroundService.Companion)
every { LocationForegroundService.isRunning } returns true
+ // Alarm plumbing is not under test here, and a plain-JVM getSystemService cannot
+ // produce a real AlarmManager.
+ mockkObject(TrackingWatchdogScheduler)
+ every { TrackingWatchdogScheduler.cancel(any()) } just Runs
+ every { TrackingWatchdogScheduler.schedule(any()) } just Runs
+
setCompanionField("reactContextRef", WeakReference(mockContext))
setCompanionField("isAppInForeground", true)
setCompanionField("activeProfileName", null)
@@ -69,6 +76,7 @@ class LocationServiceModuleTest {
unmockkStatic(Arguments::class)
unmockkObject(DatabaseHelper.Companion)
unmockkObject(LocationForegroundService.Companion)
+ unmockkObject(TrackingWatchdogScheduler)
setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))
setCompanionField("isAppInForeground", true)
setCompanionField("activeProfileName", null)
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.kt
new file mode 100644
index 00000000..885a34ae
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/TrackingWatchdogReceiverTest.kt
@@ -0,0 +1,181 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.Manifest
+import android.app.AlarmManager
+import android.app.Application
+import android.app.NotificationManager
+import android.content.Context
+import android.content.Intent
+import androidx.test.core.app.ApplicationProvider
+import com.Colota.bridge.LocationServiceModule
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.SettingsKeys
+import com.Colota.util.AppLogger
+import io.mockk.*
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+
+/**
+ * The watchdog is the only recovery that works while the app stays closed, which is the window
+ * every #444 reporter describes. Its rules: never resurrect what the user stopped, never retry
+ * forever without permission, and never go silent when it cannot restart the service itself.
+ */
+@RunWith(RobolectricTestRunner::class)
+class TrackingWatchdogReceiverTest {
+
+ private lateinit var app: Application
+ private lateinit var db: DatabaseHelper
+ private lateinit var alarmManager: AlarmManager
+ private lateinit var notificationManager: NotificationManager
+
+ private fun fire() = TrackingWatchdogReceiver().onReceive(app, Intent())
+
+ @Before
+ fun setUp() {
+ app = ApplicationProvider.getApplicationContext()
+ db = DatabaseHelper.getInstance(app)
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+
+ alarmManager = app.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ notificationManager = app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ TrackingWatchdogScheduler.cancel(app)
+ shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)
+
+ mockkObject(AppLogger)
+ every { AppLogger.d(any(), any()) } just Runs
+ every { AppLogger.i(any(), any()) } just Runs
+ every { AppLogger.w(any(), any()) } just Runs
+ every { AppLogger.e(any(), any()) } just Runs
+ every { AppLogger.e(any(), any(), any()) } just Runs
+
+ mockkObject(LocationServiceModule)
+ every { LocationServiceModule.sendTrackingStartedEvent(any()) } returns true
+ }
+
+ @After
+ fun tearDown() {
+ unmockkObject(AppLogger)
+ unmockkObject(LocationServiceModule)
+ }
+
+ @Test
+ fun `restarts a dead service the user still wants and stays armed`() {
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+
+ fire()
+
+ val started = shadowOf(app).nextStartedService
+ assertNotNull("A dead service must be restarted", started)
+ assertEquals(LocationForegroundService::class.java.name, started.component?.className)
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+ }
+
+ @Test
+ fun `leaves a live service alone and stays armed`() {
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+
+ mockkObject(LocationForegroundService.Companion)
+ try {
+ every { LocationForegroundService.isRunning } returns true
+
+ fire()
+
+ assertNull("A healthy service must not be restarted", shadowOf(app).nextStartedService)
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+ } finally {
+ unmockkObject(LocationForegroundService.Companion)
+ }
+ }
+
+ @Test
+ fun `disarms itself once the user stops tracking`() {
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+
+ fire()
+
+ assertNull("A stop must never be undone", shadowOf(app).nextStartedService)
+ assertTrue("Nothing left to watch", shadowOf(alarmManager).scheduledAlarms.isEmpty())
+ }
+
+ /**
+ * An inexact alarm does not earn the background foreground-service start exemption, so this
+ * is the ordinary outcome for anyone who has not made the app battery-unrestricted.
+ */
+ @Test
+ fun `a denied restart tells the user instead of failing silently`() {
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+
+ mockkObject(LocationForegroundService.Companion)
+ try {
+ every { LocationForegroundService.isRunning } returns false
+ every {
+ LocationForegroundService.startTracking(any(), any(), any())
+ } throws IllegalStateException("FGS start not allowed from background")
+
+ fire()
+
+ val posted = shadowOf(notificationManager).allNotifications
+ assertEquals("The user needs a way back", 1, posted.size)
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+ } finally {
+ unmockkObject(LocationForegroundService.Companion)
+ }
+ }
+
+ /**
+ * Tracking is allowed to run with notifications denied, so the tap-to-resume fallback can
+ * be unavailable exactly when it is needed. The log must then carry the evidence instead.
+ */
+ @Test
+ fun `a denied restart with notifications off records that the user could not be told`() {
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+ shadowOf(notificationManager).setNotificationsEnabled(false)
+
+ mockkObject(LocationForegroundService.Companion)
+ try {
+ every { LocationForegroundService.isRunning } returns false
+ every {
+ LocationForegroundService.startTracking(any(), any(), any())
+ } throws IllegalStateException("FGS start not allowed from background")
+
+ fire()
+
+ assertEquals("Nothing can be posted", 0, shadowOf(notificationManager).allNotifications.size)
+ verify { AppLogger.w(any(), "Cannot prompt to resume either - notifications are denied") }
+ assertEquals("Must keep trying", 1, shadowOf(alarmManager).scheduledAlarms.size)
+ } finally {
+ unmockkObject(LocationForegroundService.Companion)
+ }
+ }
+
+ @Test
+ fun `stops retrying when location permission is gone`() {
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+ shadowOf(app).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)
+
+ fire()
+
+ assertNull("Restarting without permission would fail every tick", shadowOf(app).nextStartedService)
+ assertTrue(shadowOf(alarmManager).scheduledAlarms.isEmpty())
+ }
+
+ @Test
+ fun `cancelling the watchdog leaves the geofence heartbeat armed`() {
+ GeofenceHeartbeatScheduler.schedule(app, 900_000L)
+ TrackingWatchdogScheduler.schedule(app)
+
+ TrackingWatchdogScheduler.cancel(app)
+
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+ }
+}