Skip to content

Colota - Android GPS Location tracker

feat(battery): auto-resume tracking on charger after low-battery stop (#449)

Max Dietrichc157d1ab24f3
diff --git a/apps/docs/docs/guides/battery-optimization.md b/apps/docs/docs/guides/battery-optimization.md
index 7e765098..ab06a8a3 100644
--- a/apps/docs/docs/guides/battery-optimization.md
+++ b/apps/docs/docs/guides/battery-optimization.md
@@ -12,7 +12,7 @@ Settings and tips to reduce battery usage without losing GPS fixes.
- **Notification throttling**: Max 1 update per 10 seconds, plus 2-meter movement filter
- **Batch processing**: 50 items per batch, 10 concurrent network requests
- **Smart sync**: Only syncs when queue has items and network is available
-- **Battery critical shutdown**: Stops tracking below 5% (when unplugged). The dashboard shows a "Tracking Stopped" message and a notification is displayed
+- **Battery critical shutdown & auto-resume**: Stops tracking below 5% when unplugged (the dashboard shows "Tracking Stopped" and a notification appears), then automatically resumes once you connect a charger - or on the next reboot if already plugged in. A stop you triggered yourself is never auto-resumed
## Tips
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index f81f21ac..05de1ca7 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -17,6 +17,15 @@ sidebar_position: 4
- Disable battery optimization for Colota (**Settings > Apps > Colota > Battery > Unrestricted**)
- **Samsung**: Make sure "Pause app activity if unused" is turned off for Colota (**Settings > Apps > Colota > Battery**)
+## Tracking stopped on low battery and didn't resume
+
+Colota stops tracking below 5% (when unplugged) and resumes automatically once you connect a charger. If it doesn't:
+
+- **Only battery stops auto-resume, not manual stops** - if you stopped tracking yourself, start it again from the app
+- **Don't force-stop the app** - that cancels the scheduled resume; it recovers on the next launch or reboot
+- **Set the battery to Unrestricted** (**Settings > Apps > Colota > Battery**) so the OS doesn't delay the charge-triggered resume.
+- **A non-charging cable** (data-only, or an already-full battery) may not trigger it; a reboot while plugged in will
+
## GPS accuracy is poor
- Wait for GPS lock (can take 30-60 seconds)
diff --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.kt
index bec1a066..3a8a5f93 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
@@ -11,4 +11,7 @@ object SettingsKeys {
const val PAUSE_ZONE_NAME = "pause_zone_name"
const val PAUSE_ZONE_WIFI_ACTIVE = "pause_zone_wifi_active"
const val PAUSE_ZONE_MOTIONLESS_ACTIVE = "pause_zone_motionless_active"
+
+ /** True when a low-battery (<5%) stop paused tracking - armed for charger auto-resume. */
+ const val STOPPED_BY_BATTERY = "stopped_by_battery"
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryScheduler.kt
new file mode 100644
index 00000000..4185d646
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryScheduler.kt
@@ -0,0 +1,38 @@
+/**
+ * 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 androidx.work.Constraints
+import androidx.work.ExistingWorkPolicy
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.WorkManager
+import com.Colota.util.AppLogger
+
+/**
+ * Arms / disarms the charger-gated recovery worker. Enqueued when tracking is
+ * stopped because the battery dropped below 5%; the worker fires once the device
+ * starts charging and resumes the location service. WorkManager survives process
+ * death (unlike a runtime receiver) and coalesces cable-wobble for free.
+ */
+object BatteryRecoveryScheduler {
+
+ private const val TAG = "BatteryRecoveryScheduler"
+ internal const val UNIQUE_WORK = "battery-recovery"
+
+ fun schedule(context: Context) {
+ val request = OneTimeWorkRequestBuilder<BatteryRecoveryWorker>()
+ .setConstraints(Constraints.Builder().setRequiresCharging(true).build())
+ .build()
+ WorkManager.getInstance(context.applicationContext)
+ .enqueueUniqueWork(UNIQUE_WORK, ExistingWorkPolicy.REPLACE, request)
+ AppLogger.i(TAG, "Armed battery-recovery worker (charging constraint)")
+ }
+
+ fun cancel(context: Context) {
+ WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK)
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.kt
new file mode 100644
index 00000000..f22a69f9
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BatteryRecoveryWorker.kt
@@ -0,0 +1,116 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.content.Context
+import android.content.pm.ServiceInfo
+import android.os.Build
+import androidx.core.app.NotificationCompat
+import androidx.work.CoroutineWorker
+import androidx.work.ForegroundInfo
+import androidx.work.WorkerParameters
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.SettingsKeys
+import com.Colota.util.AppLogger
+
+/**
+ * Resumes the location foreground service after a battery-critical (<5%) stop,
+ * once the device starts charging. Armed by [BatteryRecoveryScheduler] with a
+ * charging constraint. Promoting to a foreground service (mirroring
+ * AutoExportWorker) grants the "an FGS is already running" exemption so the
+ * service start is allowed from the background on Android 12+.
+ */
+class BatteryRecoveryWorker(
+ private val appContext: Context,
+ params: WorkerParameters
+) : CoroutineWorker(appContext, params) {
+
+ companion object {
+ private const val TAG = "BatteryRecoveryWorker"
+ private const val CHANNEL_ID = "battery_recovery"
+ private const val FOREGROUND_NOTIFICATION_ID = 9003
+ }
+
+ override suspend fun getForegroundInfo(): ForegroundInfo {
+ ensureNotificationChannel()
+ val notification = NotificationCompat.Builder(appContext, CHANNEL_ID)
+ .setSmallIcon(android.R.drawable.ic_menu_mylocation)
+ .setContentTitle("Resuming tracking")
+ .setContentText("Charger connected - restarting location tracking")
+ .setOngoing(true)
+ .build()
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ ForegroundInfo(FOREGROUND_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ } else {
+ ForegroundInfo(FOREGROUND_NOTIFICATION_ID, notification)
+ }
+ }
+
+ override suspend fun doWork(): Result {
+ val db = try {
+ DatabaseHelper.getInstance(appContext)
+ } catch (e: Exception) {
+ // Transient DB lock (e.g. just after boot) - let WorkManager retry.
+ AppLogger.w(TAG, "DB unavailable, will retry: ${e.message}")
+ return Result.retry()
+ }
+
+ val stoppedByBattery = db.getSetting(SettingsKeys.STOPPED_BY_BATTERY, "false") == "true"
+ if (!stoppedByBattery) {
+ AppLogger.d(TAG, "Not stopped by battery - nothing to resume")
+ return Result.success()
+ }
+
+ val alreadyTracking = db.getSetting(SettingsKeys.TRACKING_ENABLED, "false") == "true"
+ if (alreadyTracking) {
+ // Manual start / cable-wobble race already brought tracking back.
+ AppLogger.d(TAG, "Already tracking - skipping resume")
+ return Result.success()
+ }
+
+ AppLogger.i(TAG, "Charger connected after battery stop - resuming tracking")
+
+ // Some OEMs throw under aggressive background restrictions; the start
+ // often still succeeds. onStartCommand clears the flag + cancels this work.
+ try {
+ setForeground(getForegroundInfo())
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Could not promote to foreground service: ${e.message}")
+ }
+
+ return try {
+ LocationForegroundService.startTracking(appContext, db, "Charger reconnected")
+ Result.success()
+ } catch (e: SecurityException) {
+ // Missing FGS permission / background-start restriction - retrying won't help.
+ AppLogger.e(TAG, "Not allowed to resume location service", e)
+ Result.failure()
+ } catch (e: IllegalStateException) {
+ // ForegroundServiceStartNotAllowedException (API 31+) is structural, not transient.
+ AppLogger.e(TAG, "Cannot start foreground service from background", e)
+ Result.failure()
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to resume location service", e)
+ Result.retry()
+ }
+ }
+
+ private fun ensureNotificationChannel() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ val channel = NotificationChannel(
+ CHANNEL_ID,
+ "Battery Recovery",
+ NotificationManager.IMPORTANCE_LOW
+ ).apply {
+ description = "Resuming tracking after a low-battery stop"
+ }
+ nm.createNotificationChannel(channel)
+ }
+ }
+}
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 83dc82cc..6bbed6e8 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
@@ -154,6 +154,20 @@ class LocationForegroundService : Service() {
ACTION_RECHECK_PROFILES,
ACTION_STOP_REQUEST
)
+
+ /**
+ * Start path for triggers the JS bridge didn't initiate (boot, charger recovery,
+ * automation): starts the service and fires onTrackingStarted so a foreground UI
+ * re-attaches its listener. The JS bridge start skips this - JS already knows.
+ * Callers handle exceptions; a background FGS start can throw on Android 12+.
+ */
+ @JvmStatic
+ fun startTracking(context: Context, dbHelper: DatabaseHelper, startedReason: String) {
+ val intent = Intent(context, LocationForegroundService::class.java)
+ ServiceConfig.fromDatabase(dbHelper).toIntent(intent)
+ context.startForegroundService(intent)
+ LocationServiceModule.sendTrackingStartedEvent(startedReason)
+ }
}
override fun onCreate() {
@@ -286,6 +300,8 @@ class LocationForegroundService : Service() {
if (!isLightweight) {
dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+ dbHelper.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "false")
+ BatteryRecoveryScheduler.cancel(this)
}
when (action) {
@@ -404,7 +420,7 @@ class LocationForegroundService : Service() {
if (deviceInfoHelper.isBatteryCritical(threshold = 5)) {
val (level, _) = deviceInfoHelper.getCachedBatteryStatus()
AppLogger.d(TAG, "Battery critical ($level%) and unplugged - stopping service")
- stopForegroundServiceWithReason("Battery below 5% - tracking paused")
+ stopForegroundServiceWithReason("Battery below 5% - tracking paused", stoppedByBattery = true)
return
}
@@ -687,7 +703,7 @@ class LocationForegroundService : Service() {
if (deviceInfoHelper.isBatteryCritical()) {
AppLogger.d(TAG, "Battery critical ($battery%) during tracking - stopping")
- stopForegroundServiceWithReason("Battery below 5% - tracking paused")
+ stopForegroundServiceWithReason("Battery below 5% - tracking paused", stoppedByBattery = true)
return
}
@@ -1094,7 +1110,7 @@ class LocationForegroundService : Service() {
)
}
- private fun stopForegroundServiceWithReason(reason: String) {
+ private fun stopForegroundServiceWithReason(reason: String, stoppedByBattery: Boolean = false) {
AppLogger.i(TAG, "Stopping: $reason")
// Reset profile indicator in JS UI
@@ -1104,6 +1120,8 @@ class LocationForegroundService : Service() {
LocationServiceModule.sendTrackingStoppedEvent(reason)
dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+ dbHelper.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, if (stoppedByBattery) "true" else "false")
+ if (stoppedByBattery) BatteryRecoveryScheduler.schedule(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/triggers/BootReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/triggers/BootReceiver.kt
index adec691b..fa604c6a 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/triggers/BootReceiver.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/triggers/BootReceiver.kt
@@ -12,9 +12,9 @@ import android.content.Intent
import com.Colota.data.DatabaseHelper
import com.Colota.data.SettingsKeys
import com.Colota.export.AutoExportScheduler
+import com.Colota.service.BatteryRecoveryScheduler
import com.Colota.service.LocationForegroundService
import com.Colota.service.NotificationHelper
-import com.Colota.service.ServiceConfig
import com.Colota.util.AppLogger
import com.Colota.util.DeviceInfoHelper
import kotlinx.coroutines.*
@@ -99,32 +99,32 @@ class LocationBootReceiver : BroadcastReceiver() {
if (!isEnabled) {
AppLogger.d(TAG, "Boot detected but tracking disabled")
- // Re-show notification if battery is still critically low
- val deviceInfo = DeviceInfoHelper(context)
- if (deviceInfo.isBatteryCritical()) {
- AppLogger.d(TAG, "Battery still critical - showing stopped notification")
- val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
- val notificationHelper = NotificationHelper(context, notificationManager)
- notificationHelper.createChannel()
- notificationManager.notify(
- NotificationHelper.STOPPED_NOTIFICATION_ID,
- notificationHelper.buildStoppedNotification("Battery below 5% - tracking paused")
- )
+ // Charger auto-resume: only if the stop was battery-triggered (not a user stop).
+ val stoppedByBattery = dbHelper.getSetting(SettingsKeys.STOPPED_BY_BATTERY, "false") == "true"
+ if (stoppedByBattery) {
+ val deviceInfo = DeviceInfoHelper(context)
+ if (deviceInfo.isPluggedIn()) {
+ AppLogger.d(TAG, "Stopped by battery and now plugged in - resuming tracking")
+ LocationForegroundService.startTracking(context, dbHelper, "Charger reconnected on boot")
+ } else {
+ AppLogger.d(TAG, "Stopped by battery, still unplugged - arming recovery + showing notification")
+ BatteryRecoveryScheduler.schedule(context)
+ val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ val notificationHelper = NotificationHelper(context, notificationManager)
+ notificationHelper.createChannel()
+ notificationManager.notify(
+ NotificationHelper.STOPPED_NOTIFICATION_ID,
+ notificationHelper.buildStoppedNotification("Battery below 5% - tracking paused")
+ )
+ }
}
return
}
AppLogger.d(TAG, "Boot detected ($action). Restarting service...")
-
- // Load config using ServiceConfig (eliminates duplication)
- val config = ServiceConfig.fromDatabase(dbHelper)
- // Create service intent with config
- val serviceIntent = Intent(context, LocationForegroundService::class.java)
- config.toIntent(serviceIntent)
-
- context.startForegroundService(serviceIntent)
-
+ LocationForegroundService.startTracking(context, dbHelper, "Device rebooted")
+
AppLogger.d(TAG, "Service start requested successfully")
} catch (e: SecurityException) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt b/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt
index b6f6be26..178438cf 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt
@@ -7,10 +7,8 @@ package com.Colota.triggers
import android.content.Context
import android.content.Intent
-import com.Colota.bridge.LocationServiceModule
import com.Colota.data.DatabaseHelper
import com.Colota.service.LocationForegroundService
-import com.Colota.service.ServiceConfig
/**
* Shared start/stop tracking actions for external triggers (app shortcut,
@@ -19,9 +17,7 @@ import com.Colota.service.ServiceConfig
*/
object TrackingControl {
fun start(context: Context, startedReason: String) {
- val config = ServiceConfig.fromDatabase(DatabaseHelper.getInstance(context))
- context.startForegroundService(config.toIntent(Intent(context, LocationForegroundService::class.java)))
- LocationServiceModule.sendTrackingStartedEvent(startedReason)
+ LocationForegroundService.startTracking(context, DatabaseHelper.getInstance(context), startedReason)
}
// Route stop through the service so stopForegroundServiceWithReason runs - direct
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoverySchedulerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoverySchedulerTest.kt
new file mode 100644
index 00000000..cd143090
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoverySchedulerTest.kt
@@ -0,0 +1,93 @@
+/**
+ * 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 androidx.test.core.app.ApplicationProvider
+import androidx.work.Configuration
+import androidx.work.WorkInfo
+import androidx.work.WorkManager
+import androidx.work.testing.SynchronousExecutor
+import androidx.work.testing.WorkManagerTestInitHelper
+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
+
+@RunWith(RobolectricTestRunner::class)
+class BatteryRecoverySchedulerTest {
+
+ private lateinit var context: Context
+
+ private fun workInfos(): List<WorkInfo> =
+ WorkManager.getInstance(context)
+ .getWorkInfosForUniqueWork(BatteryRecoveryScheduler.UNIQUE_WORK)
+ .get()
+
+ @Before
+ fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+ val config = Configuration.Builder()
+ .setExecutor(SynchronousExecutor())
+ .build()
+ WorkManagerTestInitHelper.initializeTestWorkManager(context, config)
+
+ 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
+
+ BatteryRecoveryScheduler.cancel(context)
+ }
+
+ @After
+ fun tearDown() {
+ unmockkObject(AppLogger)
+ }
+
+ @Test
+ fun `schedule enqueues unique work that requires charging`() {
+ BatteryRecoveryScheduler.schedule(context)
+
+ val infos = workInfos()
+ assertEquals("Exactly one recovery work should be enqueued", 1, infos.size)
+ assertEquals(WorkInfo.State.ENQUEUED, infos[0].state)
+ assertTrue(
+ "Recovery work must wait for charging",
+ infos[0].constraints.requiresCharging()
+ )
+ }
+
+ @Test
+ fun `cancel removes the pending recovery work`() {
+ BatteryRecoveryScheduler.schedule(context)
+ assertEquals(1, workInfos().count { it.state == WorkInfo.State.ENQUEUED })
+
+ BatteryRecoveryScheduler.cancel(context)
+
+ assertTrue(
+ "No recovery work should remain enqueued after cancel",
+ workInfos().none { it.state == WorkInfo.State.ENQUEUED }
+ )
+ }
+
+ @Test
+ fun `scheduling twice replaces, leaving a single pending work`() {
+ BatteryRecoveryScheduler.schedule(context)
+ BatteryRecoveryScheduler.schedule(context)
+
+ assertEquals(
+ "REPLACE policy must not leave duplicate enqueued work",
+ 1,
+ workInfos().count { it.state == WorkInfo.State.ENQUEUED }
+ )
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.kt
new file mode 100644
index 00000000..cac5799b
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/BatteryRecoveryWorkerTest.kt
@@ -0,0 +1,118 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.app.Application
+import androidx.test.core.app.ApplicationProvider
+import androidx.work.ListenableWorker
+import androidx.work.testing.TestListenableWorkerBuilder
+import com.Colota.bridge.LocationServiceModule
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.SettingsKeys
+import com.Colota.util.AppLogger
+import io.mockk.*
+import kotlinx.coroutines.runBlocking
+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
+
+@RunWith(RobolectricTestRunner::class)
+class BatteryRecoveryWorkerTest {
+
+ private lateinit var app: Application
+ private lateinit var db: DatabaseHelper
+
+ private fun runWorker(): ListenableWorker.Result =
+ runBlocking { TestListenableWorkerBuilder<BatteryRecoveryWorker>(app).build().doWork() }
+
+ @Before
+ fun setUp() {
+ app = ApplicationProvider.getApplicationContext()
+ db = DatabaseHelper.getInstance(app)
+ db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "false")
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+
+ 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 `resumes the location service when stopped by battery and not tracking`() {
+ db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "true")
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+
+ val result = runWorker()
+
+ assertEquals(ListenableWorker.Result.success(), result)
+ val started = shadowOf(app).nextStartedService
+ assertNotNull("Worker should start the location service", started)
+ assertEquals(
+ LocationForegroundService::class.java.name,
+ started.component?.className
+ )
+ // The foreground UI only re-attaches its location listener on this event,
+ // so a native resume must announce it (see useLocationTracking onTrackingStarted).
+ verify { LocationServiceModule.sendTrackingStartedEvent(any()) }
+ }
+
+ @Test
+ fun `does nothing when the stop was not battery-triggered`() {
+ db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "false")
+
+ val result = runWorker()
+
+ assertEquals(ListenableWorker.Result.success(), result)
+ assertNull("No service should start for a non-battery stop", shadowOf(app).nextStartedService)
+ verify(exactly = 0) { LocationServiceModule.sendTrackingStartedEvent(any()) }
+ }
+
+ @Test
+ fun `skips resume when tracking is already active`() {
+ db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "true")
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "true")
+
+ val result = runWorker()
+
+ assertEquals(ListenableWorker.Result.success(), result)
+ assertNull("Already tracking - must not double-start", shadowOf(app).nextStartedService)
+ verify(exactly = 0) { LocationServiceModule.sendTrackingStartedEvent(any()) }
+ }
+
+ @Test
+ fun `structural FGS-start failure fails instead of retrying forever`() {
+ db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "true")
+ db.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")
+
+ mockkObject(LocationForegroundService.Companion)
+ try {
+ // ForegroundServiceStartNotAllowedException is an IllegalStateException.
+ every {
+ LocationForegroundService.startTracking(any(), any(), any())
+ } throws IllegalStateException("FGS start not allowed from background")
+
+ assertEquals(ListenableWorker.Result.failure(), runWorker())
+ } finally {
+ unmockkObject(LocationForegroundService.Companion)
+ }
+ }
+}
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 a68f11a9..0c7529ff 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
@@ -99,6 +99,10 @@ class LocationForegroundServiceTest {
every { LocationServiceModule.sendTrackingStoppedEvent(any()) } returns true
every { LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true
+ mockkObject(BatteryRecoveryScheduler)
+ every { BatteryRecoveryScheduler.schedule(any()) } just Runs
+ every { BatteryRecoveryScheduler.cancel(any()) } just Runs
+
mockkStatic(android.os.Looper::class)
every { android.os.Looper.getMainLooper() } returns mockk(relaxed = true)
@@ -118,6 +122,7 @@ class LocationForegroundServiceTest {
unmockkObject(LocationServiceModule)
unmockkObject(PayloadBuilder)
unmockkObject(AppLogger)
+ unmockkObject(BatteryRecoveryScheduler)
unmockkStatic(android.os.Looper::class)
}
@@ -1590,6 +1595,34 @@ class LocationForegroundServiceTest {
verify(exactly = 0) { LocationServiceModule.sendProfileSwitchEvent(any(), any()) }
}
+ @Test
+ fun `stopForBattery marks stopped_by_battery so charger can auto-resume`() = testScope.runTest {
+ every { deviceInfoHelper.isBatteryCritical() } returns true
+ val location = mockLocation()
+
+ invokeHandleLocationUpdate(location)
+
+ verify { dbHelper.saveSetting("stopped_by_battery", "true") }
+ }
+
+ @Test
+ fun `stopForBattery arms the charger recovery worker`() = testScope.runTest {
+ every { deviceInfoHelper.isBatteryCritical() } returns true
+ val location = mockLocation()
+
+ invokeHandleLocationUpdate(location)
+
+ verify { BatteryRecoveryScheduler.schedule(any()) }
+ }
+
+ @Test
+ fun `non-battery stop clears stopped_by_battery and does not arm recovery`() {
+ invokeStopWithReason("Location permission missing", stoppedByBattery = false)
+
+ verify { dbHelper.saveSetting("stopped_by_battery", "false") }
+ verify(exactly = 0) { BatteryRecoveryScheduler.schedule(any()) }
+ }
+
// =========================================================================
// enterPauseZone - pause flag registration
// =========================================================================
@@ -1939,6 +1972,14 @@ class LocationForegroundServiceTest {
method.invoke(service, location)
}
+ private fun invokeStopWithReason(reason: String, stoppedByBattery: Boolean) {
+ val method = LocationForegroundService::class.java.getDeclaredMethod(
+ "stopForegroundServiceWithReason", String::class.java, Boolean::class.javaPrimitiveType
+ )
+ method.isAccessible = true
+ method.invoke(service, reason, stoppedByBattery)
+ }
+
private fun invokeEnterPauseZone(geofence: GeofenceHelper.Geofence) {
val method = LocationForegroundService::class.java.getDeclaredMethod(
"enterPauseZone", GeofenceHelper.Geofence::class.java
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/triggers/LocationBootReceiverTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/triggers/LocationBootReceiverTest.kt
index 3a2c8646..c2b1676f 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/triggers/LocationBootReceiverTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/triggers/LocationBootReceiverTest.kt
@@ -9,7 +9,10 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.Colota.data.DatabaseHelper
+import com.Colota.service.BatteryRecoveryScheduler
+import com.Colota.service.NotificationHelper
import com.Colota.util.AppLogger
+import com.Colota.util.DeviceInfoHelper
import io.mockk.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
@@ -46,12 +49,19 @@ class LocationBootReceiverTest {
every { AppLogger.i(any(), any()) } just Runs
every { AppLogger.w(any(), any()) } just Runs
every { AppLogger.e(any(), any(), any()) } just Runs
+
+ // Charger-recovery branch deps; inert for the enabled/disabled paths.
+ mockkObject(BatteryRecoveryScheduler)
+ every { BatteryRecoveryScheduler.schedule(any()) } just Runs
+ mockkConstructor(DeviceInfoHelper::class)
+ mockkConstructor(NotificationHelper::class)
+ every { anyConstructed<NotificationHelper>().createChannel() } just Runs
+ every { anyConstructed<NotificationHelper>().buildStoppedNotification(any()) } returns mockk(relaxed = true)
}
@After
fun tearDown() {
- unmockkObject(AppLogger)
- unmockkObject(DatabaseHelper.Companion)
+ unmockkAll()
}
// ========================================================================
@@ -166,6 +176,35 @@ class LocationBootReceiverTest {
verify(exactly = 0) { mockContext.startService(any()) }
}
+ // ========================================================================
+ // handleBootCompleted — charger auto-resume (#281)
+ // ========================================================================
+
+ @Test
+ fun `handleBootCompleted resumes when battery-stopped and plugged in`() = runTest {
+ mockDbReadyAndDisabled()
+ every { mockDbHelper.getSetting("stopped_by_battery", "false") } returns "true"
+ every { mockDbHelper.getAllSettings() } returns mapOf("endpoint" to "https://example.com")
+ every { anyConstructed<DeviceInfoHelper>().isPluggedIn() } returns true
+
+ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)
+
+ verify { mockContext.startForegroundService(any()) }
+ verify(exactly = 0) { BatteryRecoveryScheduler.schedule(any()) }
+ }
+
+ @Test
+ fun `handleBootCompleted arms recovery when battery-stopped and unplugged`() = runTest {
+ mockDbReadyAndDisabled()
+ every { mockDbHelper.getSetting("stopped_by_battery", "false") } returns "true"
+ every { anyConstructed<DeviceInfoHelper>().isPluggedIn() } returns false
+
+ callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)
+
+ verify { BatteryRecoveryScheduler.schedule(any()) }
+ verify(exactly = 0) { mockContext.startForegroundService(any()) }
+ }
+
// ========================================================================
// waitForDatabaseReady
// ========================================================================