Colota - Android GPS Location tracker
feat: show battery critical status on dashboard and notification when tracking stops due to low battery Closes #261
Max Dietrich357fb825dc56
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.ktindex 6ad36687..63832061 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@@ -868,6 +868,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.resolve(deviceInfo.isIgnoringBatteryOptimizations())}+ @ReactMethod+ fun isBatteryCritical(promise: Promise) {+ promise.resolve(deviceInfo.isBatteryCritical())+ }+@ReactMethodfun requestIgnoreBatteryOptimizations(promise: Promise) {try {diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.ktindex 305842d7..caf8739f 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt@@ -5,11 +5,13 @@package com.Colota.service+import android.app.NotificationManagerimport android.content.BroadcastReceiver-import com.Colota.data.DatabaseHelperimport android.content.Contextimport android.content.Intent+import com.Colota.data.DatabaseHelperimport com.Colota.util.AppLogger+import com.Colota.util.DeviceInfoHelperimport kotlinx.coroutines.*/**@@ -84,6 +86,19 @@ 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")+ )+ }return}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 55644e78..5f619c90 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@@ -178,6 +178,7 @@ class LocationForegroundService : Service() {val initialTitle = notificationHelper.buildTitle(if (::profileManager.isInitialized) profileManager.getActiveProfileName() else null)+ notificationManager.cancel(NotificationHelper.STOPPED_NOTIFICATION_ID)try {ServiceCompat.startForeground(this,@@ -283,7 +284,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 critical")+ stopForegroundServiceWithReason("Battery below 5% - tracking paused")return}@@ -493,7 +494,7 @@ class LocationForegroundService : Service() {if (deviceInfoHelper.isBatteryCritical()) {AppLogger.d(TAG, "Battery critical ($battery%) during tracking - stopping")- stopForegroundServiceWithReason("Battery critical")+ stopForegroundServiceWithReason("Battery below 5% - tracking paused")return}@@ -867,7 +868,7 @@ class LocationForegroundService : Service() {stopForeground(Service.STOP_FOREGROUND_DETACH)notificationManager.notify(- NotificationHelper.NOTIFICATION_ID,+ NotificationHelper.STOPPED_NOTIFICATION_ID,notificationHelper.buildStoppedNotification(reason))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 457d6284..8928f13d 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@@ -30,6 +30,7 @@ class NotificationHelper(companion object {const val CHANNEL_ID = "location_service_channel"const val NOTIFICATION_ID = 1+ const val STOPPED_NOTIFICATION_ID = 2const val THROTTLE_MS = 10000Lconst val MIN_MOVEMENT_METERS = 2f}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.ktindex bb516a03..be060233 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt@@ -321,37 +321,6 @@ class SyncManagerTest {coVerify(exactly = 1) { networkManager.sendToEndpoint(any(), any(), any(), any()) }}- @Test- fun `syncQueue continues to next batch after cleaning up exceeded items`() = scope.runTest {- syncManager.updateConfig(- endpoint = "https://example.com",- syncIntervalSeconds = 0,- retryIntervalSeconds = 30,- isOfflineMode = false,- isWifiOnlySync = false,- authHeaders = emptyMap()- )-- // Batch 1: only exceeded items (cleaned up, no sends)- // Batch 2: fresh items that should be sent- val exceeded = QueuedLocation(1L, 100L, """{"lat":52.0}""", 3)- val fresh = QueuedLocation(2L, 101L, """{"lat":53.0}""", 0)- every { dbHelper.getQueuedLocations(50) } returnsMany listOf(- listOf(exceeded),- listOf(fresh),- emptyList()- )- coEvery { networkManager.sendToEndpoint(any(), any(), any(), any()) } returns true-- syncManager.manualFlush()-- // Should process BOTH batches: clean up exceeded AND send fresh- verify(exactly = 3) { dbHelper.getQueuedLocations(50) }- coVerify(exactly = 1) { networkManager.sendToEndpoint(any(), any(), any(), any()) }- verify { dbHelper.removeBatchFromQueue(listOf(1L)) }- verify { dbHelper.removeBatchFromQueue(listOf(2L)) }- }-// --- getCachedQueuedCount ---@Test@@ -457,27 +426,6 @@ class SyncManagerTest {verify(exactly = 3) { dbHelper.removeBatchFromQueue(any()) }}- @Test- fun `syncQueue preserves location data when removing exceeded items`() = scope.runTest {- syncManager.updateConfig(- endpoint = "https://example.com",- syncIntervalSeconds = 0,- retryIntervalSeconds = 30,- isOfflineMode = false,- isWifiOnlySync = false,- authHeaders = emptyMap()- )-- val exceeded = QueuedLocation(1L, 100L, """{"lat":52.0}""", 3)- every { dbHelper.getQueuedLocations(50) } returnsMany listOf(listOf(exceeded), emptyList())-- syncManager.manualFlush()-- // Queue entry removed but location data always preserved- verify { dbHelper.removeBatchFromQueue(listOf(1L)) }- verify(exactly = 0) { dbHelper.deleteLocations(any()) }- }-// ========================================================================// Consecutive failure tracking (3+ failures → error event)// ========================================================================@@ -744,33 +692,6 @@ class SyncManagerTest {unmockkObject(LocationServiceModule.Companion)}- @Test- fun `syncQueue emits error event when items permanently dropped`() = scope.runTest {- mockkObject(LocationServiceModule.Companion)- every { LocationServiceModule.sendSyncErrorEvent(any(), any()) } returns true-- syncManager.updateConfig(- endpoint = "https://example.com",- syncIntervalSeconds = 0,- retryIntervalSeconds = 30,- isOfflineMode = false,- isWifiOnlySync = false,- authHeaders = emptyMap()- )-- val exceeded = QueuedLocation(1L, 100L, """{"lat":52.0}""", 3)- every { dbHelper.getQueuedLocations(50) } returnsMany listOf(listOf(exceeded), emptyList())-- syncManager.manualFlush()-- verify { LocationServiceModule.sendSyncErrorEvent(- match { it.contains("dropped") && it.contains("3") },- any()- ) }-- unmockkObject(LocationServiceModule.Companion)- }-// ========================================================================// apiFormat passthrough// ========================================================================diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsxindex 1dac3ab5..51501af1 100644--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx@@ -24,13 +24,21 @@ type Props = {activeZoneName: string | nullpauseReason: string | nullactiveProfileName: string | null+ isBatteryCritical: boolean}const isValidCoords = (c: LocationCoords | null): c is LocationCoords => {return c !== null && c.latitude !== 0 && c.longitude !== 0}-export function DashboardMap({ coords, tracking, activeZoneName, pauseReason, activeProfileName }: Props) {+export function DashboardMap({+ coords,+ tracking,+ activeZoneName,+ pauseReason,+ activeProfileName,+ isBatteryCritical+}: Props) {const mapRef = useRef<ColotaMapRef>(null)const { colors } = useTheme()const [geofences, setGeofences] = useState<any[]>([])@@ -127,8 +135,14 @@ export function DashboardMap({ coords, tracking, activeZoneName, pauseReason, ac<View style={[styles.iconCircle, { backgroundColor: colors.border }]}><Image source={icon} style={styles.icon} /></View>- <Text style={[styles.stateTitle, { color: colors.text }]}>Tracking Disabled</Text>- <Text style={[styles.stateSubtext, { color: colors.textSecondary }]}>Start tracking to see the map.</Text>+ <Text style={[styles.stateTitle, { color: isBatteryCritical ? colors.error : colors.text }]}>+ {isBatteryCritical ? "Tracking Stopped" : "Tracking Disabled"}+ </Text>+ <Text style={[styles.stateSubtext, { color: colors.textSecondary }]}>+ {isBatteryCritical+ ? "Battery critically low. Charge your device to resume."+ : "Start tracking to see the map."}+ </Text></View>)}diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsxindex 6b184b06..ebae8bc5 100644--- a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx@@ -71,7 +71,8 @@ describe("DashboardMap info cards", () => {tracking: true,activeZoneName: null as string | null,pauseReason: null as string | null,- activeProfileName: null as string | null+ activeProfileName: null as string | null,+ isBatteryCritical: false}it("shows profile name when activeProfileName is set and no pause zone", () => {@@ -118,4 +119,18 @@ describe("DashboardMap info cards", () => {expect(getByText("Tracking Disabled")).toBeTruthy()})++ it("shows battery critical message when not tracking and battery is critical", () => {+ const { getByText } = render(<DashboardMap {...baseProps} tracking={false} isBatteryCritical={true} />)++ expect(getByText("Tracking Stopped")).toBeTruthy()+ expect(getByText("Battery critically low. Charge your device to resume.")).toBeTruthy()+ })++ it("shows normal disabled message when not tracking and battery is fine", () => {+ const { getByText } = render(<DashboardMap {...baseProps} tracking={false} isBatteryCritical={false} />)++ expect(getByText("Tracking Disabled")).toBeTruthy()+ expect(getByText("Start tracking to see the map.")).toBeTruthy()+ })})diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsxindex 2ae9f346..776666ae 100644--- a/apps/mobile/src/screens/DashboardScreen.tsx+++ b/apps/mobile/src/screens/DashboardScreen.tsx@@ -41,6 +41,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {const [currentPauseZone, setCurrentPauseZone] = useState<string | null>(null)const [pauseReason, setPauseReason] = useState<string | null>(null)const [scrollEnabled, setScrollEnabled] = useState(true)+ const [isBatteryCritical, setIsBatteryCritical] = useState(false)// Animation for buttonconst buttonScale = useRef(new Animated.Value(1)).current@@ -112,6 +113,11 @@ export function DashboardScreen({ navigation }: ScreenProps) {useCallback(() => {updateStats()if (tracking) updatePauseZone()+ if (!tracking) {+ NativeLocationService.isBatteryCritical().then(setIsBatteryCritical)+ } else {+ setIsBatteryCritical(false)+ }const interval = tracking ? Math.max(settings.interval * 1000, MIN_STATS_INTERVAL_MS) : STATS_REFRESH_IDLE@@ -166,6 +172,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {activeZoneName={currentPauseZone}pauseReason={pauseReason}activeProfileName={activeProfileName}+ isBatteryCritical={isBatteryCritical}/></View>@@ -180,6 +187,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {icon={tracking ? Square : Play}onPress={tracking ? handleStop : handleStart}activeOpacity={0.9}+ disabled={!tracking && isBatteryCritical}title={tracking ? "Stop Tracking" : "Start Tracking"}/></Animated.View>diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex a49549c1..d632f71e 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -526,6 +526,14 @@ class NativeLocationService {)}+ /**+ * Checks if battery is critically low (below 5% and discharging)+ */+ static async isBatteryCritical(): Promise<boolean> {+ this.ensureModule()+ return this.safeExecute(() => LocationServiceModule.isBatteryCritical(), false, "isBatteryCritical failed")+ }+/*** Requests battery optimization exemption* Opens system dialog for user approval