Colota - Android GPS Location tracker
Fix notification bugs and extract NotificationHelper
Max Dietrich2d7eddee5cbb
diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.ymlindex 029afc00..29baa16d 100644--- a/.github/workflows/build-release.yml+++ b/.github/workflows/build-release.yml@@ -33,12 +33,12 @@ jobs:- run: npx -w @colota/mobile tsc --noEmit- run: npm test -w @colota/mobile- build-and-release:- name: Build & Publish Release+ build:+ name: Build Release APKsneeds: testruns-on: ubuntu-latestpermissions:- contents: write+ contents: readsteps:- name: Checkout code@@ -114,16 +114,13 @@ jobs:-Pandroid.useAndroidX=true \-Dorg.gradle.jvmargs="-Xmx4096m -XX:MaxMetaspaceSize=512m"- - name: Publish to GitHub Release- uses: softprops/action-gh-release@v2+ - name: Upload APKs+ uses: actions/upload-artifact@v4with:- files: |- apps/mobile/android/app/build/outputs/apk/gms/release/app-gms-arm64-v8a-release.apk- apps/mobile/android/app/build/outputs/apk/gms/release/app-gms-armeabi-v7a-release.apk- apps/mobile/android/app/build/outputs/apk/foss/release/app-foss-arm64-v8a-release.apk- apps/mobile/android/app/build/outputs/apk/foss/release/app-foss-armeabi-v7a-release.apk- env:- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ name: release-apks+ path: |+ apps/mobile/android/app/build/outputs/apk/gms/release/*.apk+ apps/mobile/android/app/build/outputs/apk/foss/release/*.apk- name: Secure Cleanupif: always()diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex cfe94112..07d2fa60 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -83,11 +83,20 @@ Each flavor provides a `LocationProviderFactory` that returns the correct implemAn Android foreground service that runs continuously for GPS tracking. Manages:- GPS location capture via the `LocationProvider` abstraction-- Foreground notification (required by Android)- Pause zone detection (geofencing)+- Battery critical shutdown (1-4% while discharging)- Location accuracy filtering- Queuing data for server sync+### NotificationHelper++Handles all notification logic for the tracking service:++- Channel creation and notification building+- Status text generation (coordinates, sync status, pause zones)+- Throttled updates (10s minimum interval, 2m minimum movement)+- Deduplication to avoid unnecessary notification redraws+### DatabaseHelperSQLite database singleton with four tables:diff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.mdindex db8b809c..a56b7d54 100644--- a/apps/docs/docs/development/local-setup.md+++ b/apps/docs/docs/development/local-setup.md@@ -111,7 +111,7 @@ colota/│ │ │ └── app/src/│ │ │ ├── main/java/com/colota/│ │ │ │ ├── bridge/ # React Native bridge-│ │ │ │ ├── service/ # Foreground service & config+│ │ │ │ ├── service/ # Foreground service, config & notifications│ │ │ │ ├── data/ # SQLite & geofencing│ │ │ │ ├── sync/ # Network sync & payloads│ │ │ │ ├── util/ # Helpers & encryption@@ -165,7 +165,8 @@ Test files are located in `apps/mobile/android/app/src/test/java/com/Colota/`. T- **DatabaseHelper** — Data model, cutoff calculations, batch operations- **SecureStorageHelper** — Basic Auth, Bearer token, custom headers, JSON parsing- **DeviceInfoHelper** — Battery threshold logic, status code mapping, percentage calculation-- **LocationForegroundService** — Notification throttling, sync formatting, zone state machine, battery shutdown+- **NotificationHelper** — Status text generation, throttling, movement filter, deduplication+- **LocationForegroundService** — Battery shutdown, accuracy filtering, zone state machine- **ServiceConfig** — Database/Intent/ReadableMap parsing, defaults, round-trips- **PayloadBuilder** — JSON payload construction and field map parsing- **GeofenceHelper** — Haversine distance calculations and radius checksdiff --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 2d5f214f..f4e5e6d3 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@@ -279,25 +279,28 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :deleted}- @ReactMethod- fun clearQueue(promise: Promise) = executeAsync(promise) {+ @ReactMethod+ fun clearQueue(promise: Promise) = executeAsync(promise) {val deleted = dbHelper.clearQueue()+ refreshNotificationIfTracking()moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }- deleted+ deleted}- @ReactMethod- fun clearAllLocations(promise: Promise) = executeAsync(promise) {+ @ReactMethod+ fun clearAllLocations(promise: Promise) = executeAsync(promise) {val deleted = dbHelper.clearAllLocations()+ refreshNotificationIfTracking()moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }deleted}@ReactMethod- fun deleteOlderThan(days: Int, promise: Promise) = executeAsync(promise) {+ fun deleteOlderThan(days: Int, promise: Promise) = executeAsync(promise) {val deleted = dbHelper.deleteOlderThan(days)+ refreshNotificationIfTracking()moduleScope.launch(Dispatchers.IO) { dbHelper.vacuum() }- deleted+ deleted}@ReactMethod@@ -314,6 +317,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ private fun refreshNotificationIfTracking() {+ val isTracking = dbHelper.getSetting("tracking_enabled", "false") == "true"+ if (isTracking) {+ try {+ startServiceWithAction(LocationForegroundService.ACTION_REFRESH_NOTIFICATION)+ } catch (e: Exception) {+ Log.w(TAG, "Notification refresh skipped: service not running", e)+ }+ }+ }+/*** Creates a geofence and invalidates cache to ensure the* Foreground Service recognizes the change immediately.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 82987bd0..b1ea0d19 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@@ -2,13 +2,11 @@* Copyright (C) 2026 Max Dietrich* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-+package com.Colota.serviceimport android.app.*import com.Colota.BuildConfig-import com.Colota.MainActivity-import com.Colota.Rimport com.Colota.bridge.LocationServiceModuleimport com.Colota.data.DatabaseHelperimport com.Colota.data.GeofenceHelper@@ -20,12 +18,11 @@ import com.Colota.util.SecureStorageHelperimport android.content.Intentimport android.os.*import android.util.Log-import androidx.core.app.NotificationCompatimport com.Colota.location.LocationProviderimport com.Colota.location.LocationProviderFactoryimport com.Colota.location.LocationUpdateCallbackimport kotlinx.coroutines.*-import org.json.JSONObject+import java.util.Locale/*** Foreground Service for continuous background location tracking.@@ -34,6 +31,7 @@ class LocationForegroundService : Service() {private lateinit var locationProvider: LocationProviderprivate lateinit var notificationManager: NotificationManager+ private lateinit var notificationHelper: NotificationHelperprivate lateinit var dbHelper: DatabaseHelperprivate lateinit var payloadBuilder: PayloadBuilderprivate lateinit var deviceInfoHelper: DeviceInfoHelper@@ -41,35 +39,36 @@ class LocationForegroundService : Service() {private lateinit var geofenceHelper: GeofenceHelperprivate lateinit var secureStorage: SecureStorageHelperprivate lateinit var syncManager: SyncManager-+@Volatile private var serviceScope: CoroutineScope? = null@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null@Volatile private var insidePauseZone = false@Volatile private var currentZoneName: String? = null- private var lastNotificationText: String? = null-- private var lastNotificationTime: Long = 0- private val NOTIFICATION_THROTTLE_MS = 10000L@Volatile private var lastKnownLocation: android.location.Location? = null- private var lastNotificationCoords: Pair<Double, Double>? = nullprivate lateinit var config: ServiceConfigprivate var fieldMap: Map<String, String>? = nullprivate var customFields: Map<String, String>? = null- private val CHANNEL_ID = "location_service_channel"- private val NOTIFICATION_ID = 1-companion object {private const val TAG = "LocationService"const val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"const val ACTION_FORCE_EXIT_ZONE = "com.Colota.FORCE_EXIT_ZONE"+ const val ACTION_REFRESH_NOTIFICATION = "com.Colota.REFRESH_NOTIFICATION"++ /** Actions that skip config reload and preserve current notification state. */+ private val LIGHTWEIGHT_ACTIONS = setOf(+ ACTION_MANUAL_FLUSH,+ ACTION_RECHECK_ZONE,+ ACTION_FORCE_EXIT_ZONE,+ ACTION_REFRESH_NOTIFICATION+ )}override fun onCreate() {super.onCreate()-+serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())locationProvider = LocationProviderFactory.create(this)@@ -82,7 +81,8 @@ class LocationForegroundService : Service() {secureStorage = SecureStorageHelper.getInstance(this)syncManager = SyncManager(dbHelper, networkManager, serviceScope!!)- createNotificationChannel()+ notificationHelper = NotificationHelper(this, notificationManager)+ notificationHelper.createChannel()}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {@@ -102,16 +102,38 @@ class LocationForegroundService : Service() {return START_NOT_STICKY}- loadConfigFromIntent(intent)- startForegroundServiceWithNotification()-val action = intent?.action-- if (action != ACTION_RECHECK_ZONE && action != ACTION_MANUAL_FLUSH && action != ACTION_FORCE_EXIT_ZONE) {+ val isLightweight = action in LIGHTWEIGHT_ACTIONS++ // Only reload config for full starts (not lightweight actions)+ if (!isLightweight) {+ loadConfigFromIntent(intent)+ }++ // Must call startForeground within 5s — use best available status+ val initialStatus = notificationHelper.getInitialStatus(+ insidePauseZone, currentZoneName, lastKnownLocation+ )+ startForeground(+ NotificationHelper.NOTIFICATION_ID,+ notificationHelper.buildTrackingNotification(initialStatus)+ )++ if (!isLightweight) {dbHelper.saveSetting("tracking_enabled", "true")}when (action) {+ ACTION_REFRESH_NOTIFICATION -> {+ syncManager.invalidateQueueCache()+ val loc = lastKnownLocation+ updateNotification(+ lat = loc?.latitude,+ lon = loc?.longitude,+ forceUpdate = true+ )+ return START_STICKY+ }ACTION_FORCE_EXIT_ZONE -> {if (insidePauseZone) {if (BuildConfig.DEBUG) {@@ -157,11 +179,11 @@ class LocationForegroundService : Service() {override fun onDestroy() {stopLocationUpdates()syncManager.stopPeriodicSync()-+serviceScope?.cancel()serviceScope = null-- notificationManager.cancel(NOTIFICATION_ID)++ notificationManager.cancel(NotificationHelper.NOTIFICATION_ID)super.onDestroy()}@@ -224,7 +246,7 @@ class LocationForegroundService : Service() {val cachedLoc = lastKnownLocationval now = System.currentTimeMillis()-+// If we have a fresh location (less than 1 min old), recheck immediatelyif (cachedLoc != null && (now - cachedLoc.time) < 60000) {recheckZoneWithLocation(cachedLoc)@@ -256,7 +278,7 @@ class LocationForegroundService : Service() {}}-+private fun recheckZoneWithLocation(location: android.location.Location) {val zoneName = geofenceHelper.getPauseZone(location)@@ -265,7 +287,7 @@ class LocationForegroundService : Service() {zoneName != null && (!insidePauseZone || zoneName != currentZoneName) -> {enterPauseZone(zoneName)}-+// Just exited pause zonezoneName == null && insidePauseZone -> {exitPauseZone()@@ -274,7 +296,7 @@ class LocationForegroundService : Service() {// Still in the same pause zone - update coords but keep paused statuszoneName != null && insidePauseZone && zoneName == currentZoneName -> {updateNotification(- lat = location.latitude,+ lat = location.latitude,lon = location.longitude,pausedInZone = true,zoneName = currentZoneName,@@ -285,7 +307,7 @@ class LocationForegroundService : Service() {// Standard movement (no zone) - show coordselse -> {updateNotification(- location.latitude,+ location.latitude,location.longitude,forceUpdate = true)@@ -395,65 +417,13 @@ class LocationForegroundService : Service() {} ?: run {updateNotification(forceUpdate = true)}-+LocationServiceModule.sendPauseZoneEvent(false, exited)if (BuildConfig.DEBUG) Log.d(TAG, "Exited pause zone: $exited")}- private fun createNotificationChannel() {- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {- val channel = NotificationChannel(- CHANNEL_ID,- "Location Tracking",- NotificationManager.IMPORTANCE_LOW- ).apply {- description = "Shows active tracking status and sync queue"- setShowBadge(false)- }- notificationManager.createNotificationChannel(channel)- }- }-- private fun buildNotification(statusText: String): Notification {- val pendingIntent = PendingIntent.getActivity(- this,- 0,- Intent(this, MainActivity::class.java),- PendingIntent.FLAG_IMMUTABLE- )-- return NotificationCompat.Builder(this, CHANNEL_ID)- .setContentTitle("Colota Tracking")- .setContentText(statusText)- .setSmallIcon(android.R.drawable.ic_menu_mylocation)- .setOngoing(true)- .setSilent(true)- .setContentIntent(pendingIntent)- .setPriority(NotificationCompat.PRIORITY_LOW)- .build()- }-- private fun getTimeSinceLastSync(): String {- val lastSuccessfulSyncTime = syncManager.lastSuccessfulSyncTime- if (lastSuccessfulSyncTime == 0L) {- return "Never"- }-- val elapsedMs = System.currentTimeMillis() - lastSuccessfulSyncTime- val elapsedMinutes = (elapsedMs / 60000).toInt()-- return when {- elapsedMinutes < 1 -> "Just now"- elapsedMinutes == 1 -> "1 min ago"- elapsedMinutes < 60 -> "$elapsedMinutes min ago"- elapsedMinutes < 120 -> "1h ago"- else -> "${elapsedMinutes / 60} h ago"- }- }-/**- * Throttled notification updates. Skips unless forceUpdate, zone change,- * or both 10s elapsed AND moved >2m. Deduplicates via text comparison.+ * Thin wrapper that delegates to NotificationHelper with current service state.*/private fun updateNotification(lat: Double? = null,@@ -462,75 +432,18 @@ class LocationForegroundService : Service() {zoneName: String? = null,forceUpdate: Boolean = false) {- val now = System.currentTimeMillis()- val lastCoords = lastNotificationCoords-- // Apply smart filtering unless forced (zone changes always pass forceUpdate=true)- if (!forceUpdate && lat != null && lon != null) {- // Throttle: don't update more than once per 10 seconds- if ((now - lastNotificationTime) < NOTIFICATION_THROTTLE_MS) {- return- }-- // Distance check: only update if moved >2 meters- if (lastCoords != null) {- val distance = FloatArray(1)- android.location.Location.distanceBetween(- lastCoords.first, lastCoords.second,- lat, lon,- distance- )-- // Skip if moved <2m- if (distance[0] < 2) {- return- }- }- }-- lastNotificationTime = now- if (lat != null && lon != null) {- lastNotificationCoords = Pair(lat, lon)- }-- val queuedCount = syncManager.getCachedQueuedCount()val isCurrentlyPaused = pausedInZone || insidePauseZoneval activeZone = zoneName ?: currentZoneName- val statusText = when {- isCurrentlyPaused -> "Paused: ${activeZone ?: "Unknown"}"- lat != null && lon != null -> {- val coords = "%.5f, %.5f".format(lat, lon)- if (queuedCount > 0 && syncManager.lastSuccessfulSyncTime > 0) {- "$coords (Last sync: ${getTimeSinceLastSync()})"- } else if (queuedCount > 0) {- "$coords (Queued: $queuedCount)"- } else if (syncManager.lastSuccessfulSyncTime > 0) {- "$coords (Synced)"- } else {- coords- }- }- else -> "Searching GPS..."- }-- val cacheKey = "$statusText-$queuedCount"- if (cacheKey != lastNotificationText) {- lastNotificationText = cacheKey- notificationManager.notify(NOTIFICATION_ID, buildNotification(statusText))- }- }-- /** Must be called within 5s of startForegroundService() per Android requirement. */- private fun startForegroundServiceWithNotification() {- val initialStatus = if (insidePauseZone) {- "Paused: ${currentZoneName ?: "Unknown"}"- } else {- "Searching GPS..."- }-- val notification = buildNotification(initialStatus)- startForeground(NOTIFICATION_ID, notification)+ notificationHelper.update(+ lat = lat,+ lon = lon,+ isPaused = isCurrentlyPaused,+ zoneName = activeZone,+ queuedCount = syncManager.getCachedQueuedCount(),+ lastSyncTime = syncManager.lastSuccessfulSyncTime,+ forceUpdate = forceUpdate+ )}private fun stopForegroundServiceWithReason(reason: String) {@@ -541,14 +454,6 @@ class LocationForegroundService : Service() {LocationServiceModule.sendTrackingStoppedEvent(reason)dbHelper.saveSetting("tracking_enabled", "false")- val finalNotification = NotificationCompat.Builder(this, CHANNEL_ID)- .setContentTitle("Colota: Stopped")- .setContentText(reason)- .setSmallIcon(android.R.drawable.ic_lock_power_off)- .setOngoing(false)- .setAutoCancel(true)- .build()-if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {stopForeground(Service.STOP_FOREGROUND_DETACH)} else {@@ -556,7 +461,10 @@ class LocationForegroundService : Service() {stopForeground(false)}- notificationManager.notify(NOTIFICATION_ID, finalNotification)+ notificationManager.notify(+ NotificationHelper.NOTIFICATION_ID,+ notificationHelper.buildStoppedNotification(reason)+ )locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }stopSelf()@@ -590,7 +498,7 @@ class LocationForegroundService : Service() {if (BuildConfig.DEBUG) {val batteryStatusStr = deviceInfoHelper.getBatteryStatusString()-+Log.d(TAG, """╔════════════════════════════════════════════════════════════════╗║ COLOTA LOCATION SERVICE CONFIGURATION ║@@ -613,14 +521,14 @@ class LocationForegroundService : Service() {║ PERFORMANCE OPTIMIZATION ║╟────────────────────────────────────────────────────────────────╢║ Battery Check Cache: 60s (managed by DeviceInfoHelper)- ║ Notification Throttle: ${NOTIFICATION_THROTTLE_MS/1000}s+ ║ Notification Throttle: ${NotificationHelper.THROTTLE_MS/1000}s╟────────────────────────────────────────────────────────────────╢║ FIELD MAPPING ║╟────────────────────────────────────────────────────────────────╢║ Custom Fields: ${if(fieldMap != null && fieldMap!!.isNotEmpty()) "✓ YES (${fieldMap!!.size} mappings)" else "✗ Using Defaults"}${if(fieldMap != null && fieldMap!!.isNotEmpty()) {- fieldMap!!.entries.joinToString("\n") {- "║ ${it.key.padEnd(20)} → ${it.value}"+ fieldMap!!.entries.joinToString("\n") {+ "║ ${it.key.padEnd(20)} → ${it.value}"}} else ""}╟────────────────────────────────────────────────────────────────╢@@ -630,8 +538,8 @@ class LocationForegroundService : Service() {║ Pause Zone: ${if(insidePauseZone) "⏸️ PAUSED in '$currentZoneName'" else "✓ Not in zone"}║ Battery Level: $batteryStatusStr║ Queued Locations: ${syncManager.getCachedQueuedCount()} items- ║ Last Sync: ${getTimeSinceLastSync()}- ║ Last Location: ${if(lastKnownLocation != null) "%.5f, %.5f".format(lastKnownLocation!!.latitude, lastKnownLocation!!.longitude) else "N/A"}+ ║ Last Sync: ${notificationHelper.formatTimeSinceSync(syncManager.lastSuccessfulSyncTime)}+ ║ Last Location: ${if(lastKnownLocation != null) String.format(Locale.US, "%.5f, %.5f", lastKnownLocation!!.latitude, lastKnownLocation!!.longitude) else "N/A"}╚════════════════════════════════════════════════════════════════╝""".trimIndent())}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.ktnew file mode 100644index 00000000..e4208922--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt@@ -0,0 +1,196 @@+/**+ * 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.*+import android.content.Context+import android.content.Intent+import android.os.Build+import androidx.core.app.NotificationCompat+import com.Colota.MainActivity+import java.util.Locale++/**+ * Handles all notification-related logic for the location tracking service:+ * channel creation, notification building, status text generation,+ * throttling, movement filtering, and deduplication.+ */+class NotificationHelper(+ private val context: Context,+ private val notificationManager: NotificationManager+) {++ private var lastText: String? = null+ private var lastUpdateTime: Long = 0+ private var lastCoords: Pair<Double, Double>? = null+ private var lastQueuedCount: Int = 0++ companion object {+ const val CHANNEL_ID = "location_service_channel"+ const val NOTIFICATION_ID = 1+ const val THROTTLE_MS = 10000L+ const val MIN_MOVEMENT_METERS = 2f+ }++ fun createChannel() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val channel = NotificationChannel(+ CHANNEL_ID,+ "Location Tracking",+ NotificationManager.IMPORTANCE_LOW+ ).apply {+ description = "Shows active tracking status and sync queue"+ setShowBadge(false)+ }+ notificationManager.createNotificationChannel(channel)+ }+ }++ fun buildTrackingNotification(statusText: String): Notification {+ val pendingIntent = PendingIntent.getActivity(+ context,+ 0,+ Intent(context, MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE+ )++ return NotificationCompat.Builder(context, CHANNEL_ID)+ .setContentTitle("Colota Tracking")+ .setContentText(statusText)+ .setSmallIcon(android.R.drawable.ic_menu_mylocation)+ .setOngoing(true)+ .setSilent(true)+ .setContentIntent(pendingIntent)+ .setPriority(NotificationCompat.PRIORITY_LOW)+ .build()+ }++ fun buildStoppedNotification(reason: String): Notification {+ return NotificationCompat.Builder(context, CHANNEL_ID)+ .setContentTitle("Colota: Stopped")+ .setContentText(reason)+ .setSmallIcon(android.R.drawable.ic_lock_power_off)+ .setOngoing(false)+ .setAutoCancel(true)+ .build()+ }++ /**+ * Returns the best status text for the initial startForeground notification.+ */+ fun getInitialStatus(+ insidePauseZone: Boolean,+ currentZoneName: String?,+ lastKnownLocation: android.location.Location?+ ): String = when {+ insidePauseZone -> "Paused: ${currentZoneName ?: "Unknown"}"+ lastKnownLocation != null -> String.format(+ Locale.US, "%.5f, %.5f",+ lastKnownLocation.latitude, lastKnownLocation.longitude+ )+ else -> "Searching GPS..."+ }++ /**+ * Builds the notification status text from current tracking state.+ */+ fun buildStatusText(+ isPaused: Boolean,+ zoneName: String?,+ lat: Double?,+ lon: Double?,+ queuedCount: Int,+ lastSyncTime: Long+ ): String = when {+ isPaused -> "Paused: ${zoneName ?: "Unknown"}"+ lat != null && lon != null -> {+ val coords = String.format(Locale.US, "%.5f, %.5f", lat, lon)+ if (queuedCount > 0 && lastSyncTime > 0) {+ "$coords (Queued: $queuedCount · ${formatTimeSinceSync(lastSyncTime)})"+ } else if (queuedCount > 0) {+ "$coords (Queued: $queuedCount)"+ } else if (lastSyncTime > 0) {+ "$coords (Synced)"+ } else {+ coords+ }+ }+ else -> "Searching GPS..."+ }++ /**+ * Formats elapsed time since last successful sync.+ */+ fun formatTimeSinceSync(lastSyncTime: Long, now: Long = System.currentTimeMillis()): String {+ if (lastSyncTime == 0L) return "Never"++ val elapsedMs = now - lastSyncTime+ val elapsedMinutes = (elapsedMs / 60000).toInt()++ return when {+ elapsedMinutes < 1 -> "Just now"+ elapsedMinutes == 1 -> "1 min ago"+ elapsedMinutes < 60 -> "$elapsedMinutes min ago"+ elapsedMinutes < 120 -> "1h ago"+ else -> "${elapsedMinutes / 60} h ago"+ }+ }++ /** Returns true if the update should be suppressed (too soon since last update). */+ fun shouldThrottle(now: Long): Boolean = (now - lastUpdateTime) < THROTTLE_MS++ /** Returns true if movement is below the minimum threshold. */+ fun shouldFilterByMovement(distanceMeters: Float): Boolean = distanceMeters < MIN_MOVEMENT_METERS++ /**+ * Full notification update with throttle, movement filter, and dedup.+ * Returns true if the notification was actually posted.+ */+ fun update(+ lat: Double? = null,+ lon: Double? = null,+ isPaused: Boolean = false,+ zoneName: String? = null,+ queuedCount: Int = 0,+ lastSyncTime: Long = 0L,+ forceUpdate: Boolean = false+ ): Boolean {+ val now = System.currentTimeMillis()++ val queueCountChanged = queuedCount != lastQueuedCount++ // Throttle + movement filter (zone changes always pass forceUpdate=true)+ // Bypass movement filter when queue count changed so status text stays current+ if (!forceUpdate && !queueCountChanged && lat != null && lon != null) {+ if (shouldThrottle(now)) return false++ val prev = lastCoords+ if (prev != null) {+ val distance = FloatArray(1)+ android.location.Location.distanceBetween(+ prev.first, prev.second, lat, lon, distance+ )+ if (shouldFilterByMovement(distance[0])) return false+ }+ }++ lastUpdateTime = now+ if (lat != null && lon != null) {+ lastCoords = Pair(lat, lon)+ }++ val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime)++ // Dedup: skip if notification text hasn't changed+ val cacheKey = "$statusText-$queuedCount"+ if (cacheKey == lastText) return false++ lastText = cacheKey+ lastQueuedCount = queuedCount+ notificationManager.notify(NOTIFICATION_ID, buildTrackingNotification(statusText))+ return true+ }+}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 968eaedb..d49ba5bf 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@@ -2,204 +2,19 @@ package com.Colota.serviceimport org.junit.Assert.*import org.junit.Test-import java.util.Locale/*** Tests for LocationForegroundService's pure logic:- * - Notification throttling decisions- * - Time-since-last-sync formatting- * - Notification status text generation* - Battery critical shutdown conditions during tracking+ * - Accuracy filter decisions+ * - Zone transition state machine*+ * Notification logic tests are in NotificationHelperTest.* The actual Android Service lifecycle and LocationProvider interactions* are not tested here (require instrumented tests).*/class LocationForegroundServiceTest {- // --- Notification throttle logic ----- @Test- fun `notification updates within 10s are throttled`() {- val lastUpdate = 1000L- val now = 5000L- val throttleMs = 10000L-- val shouldThrottle = (now - lastUpdate) < throttleMs- assertTrue(shouldThrottle)- }-- @Test- fun `notification updates after 10s are allowed`() {- val lastUpdate = 1000L- val now = 12000L- val throttleMs = 10000L-- val shouldThrottle = (now - lastUpdate) < throttleMs- assertFalse(shouldThrottle)- }-- @Test- fun `notification updates at exactly 10s are allowed`() {- val lastUpdate = 1000L- val now = 11000L- val throttleMs = 10000L-- val shouldThrottle = (now - lastUpdate) < throttleMs- assertFalse(shouldThrottle)- }-- // --- Movement filter logic ----- @Test- fun `movement less than 2m is filtered`() {- val distanceMeters = 1.5f- val shouldFilter = distanceMeters < 2- assertTrue(shouldFilter)- }-- @Test- fun `movement of exactly 2m is not filtered`() {- val distanceMeters = 2.0f- val shouldFilter = distanceMeters < 2- assertFalse(shouldFilter)- }-- @Test- fun `movement greater than 2m is not filtered`() {- val distanceMeters = 5.0f- val shouldFilter = distanceMeters < 2- assertFalse(shouldFilter)- }-- // --- getTimeSinceLastSync formatting ----- @Test- fun `time since sync shows Never when no sync happened`() {- assertEquals("Never", formatTimeSinceSync(lastSyncTime = 0L, now = 1000L))- }-- @Test- fun `time since sync shows Just now for less than 1 min`() {- val now = 100000L- val lastSync = now - 30000L // 30 seconds ago- assertEquals("Just now", formatTimeSinceSync(lastSync, now))- }-- @Test- fun `time since sync shows 1 min ago`() {- val now = 100000L- val lastSync = now - 60000L // exactly 1 minute- assertEquals("1 min ago", formatTimeSinceSync(lastSync, now))- }-- @Test- fun `time since sync shows N min ago for less than 1 hour`() {- val now = 100000L- val lastSync = now - 1500000L // 25 minutes- assertEquals("25 min ago", formatTimeSinceSync(lastSync, now))- }-- @Test- fun `time since sync shows 1h ago for 60-119 minutes`() {- val now = 10000000L- val lastSync = now - 3600000L // 60 minutes- assertEquals("1h ago", formatTimeSinceSync(lastSync, now))- }-- @Test- fun `time since sync shows Nh ago for 120+ minutes`() {- val now = 10000000L- val lastSync = now - 7200000L // 120 minutes- assertEquals("2 h ago", formatTimeSinceSync(lastSync, now))- }-- @Test- fun `time since sync shows 5h ago for 300 minutes`() {- val now = 100000000L- val lastSync = now - 18000000L // 300 minutes- assertEquals("5 h ago", formatTimeSinceSync(lastSync, now))- }-- // --- Notification status text generation ----- @Test- fun `status text shows Paused with zone name when in pause zone`() {- val text = buildStatusText(- isPaused = true,- zoneName = "Home",- lat = 52.0,- lon = 13.0,- queuedCount = 0,- lastSyncTime = 0L- )- assertEquals("Paused: Home", text)- }-- @Test- fun `status text shows Paused Unknown when zone name is null`() {- val text = buildStatusText(- isPaused = true,- zoneName = null,- lat = 52.0,- lon = 13.0,- queuedCount = 0,- lastSyncTime = 0L- )- assertEquals("Paused: Unknown", text)- }-- @Test- fun `status text shows coordinates when tracking normally`() {- val text = buildStatusText(- isPaused = false,- zoneName = null,- lat = 52.51630,- lon = 13.37770,- queuedCount = 0,- lastSyncTime = 0L- )- assertEquals("52.51630, 13.37770", text)- }-- @Test- fun `status text shows Synced when queue empty and has synced`() {- val text = buildStatusText(- isPaused = false,- zoneName = null,- lat = 52.0,- lon = 13.0,- queuedCount = 0,- lastSyncTime = System.currentTimeMillis()- )- assertEquals("52.00000, 13.00000 (Synced)", text)- }-- @Test- fun `status text shows queued count when has queue but never synced`() {- val text = buildStatusText(- isPaused = false,- zoneName = null,- lat = 52.0,- lon = 13.0,- queuedCount = 15,- lastSyncTime = 0L- )- assertEquals("52.00000, 13.00000 (Queued: 15)", text)- }-- @Test- fun `status text shows Searching GPS when no coordinates`() {- val text = buildStatusText(- isPaused = false,- zoneName = null,- lat = null,- lon = null,- queuedCount = 0,- lastSyncTime = 0L- )- assertEquals("Searching GPS...", text)- }-// --- Battery critical during tracking (handleLocationUpdate logic) ---@Test@@ -321,75 +136,9 @@ class LocationForegroundServiceTest {assertTrue(shouldReEnter)}- // --- Deduplication logic ----- @Test- fun `same notification text is deduplicated`() {- val lastText = "52.52000, 13.40500-3"- val newText = "52.52000, 13.40500-3"- assertFalse(shouldUpdateNotification(lastText, newText))- }-- @Test- fun `different notification text is not deduplicated`() {- val lastText = "52.52000, 13.40500-3"- val newText = "52.52100, 13.40600-3"- assertTrue(shouldUpdateNotification(lastText, newText))- }-- @Test- fun `first notification update always proceeds`() {- assertTrue(shouldUpdateNotification(null, "52.52000, 13.40500-0"))- }-// --- Helper methods replicating logic under test ---- private fun formatTimeSinceSync(lastSyncTime: Long, now: Long): String {- if (lastSyncTime == 0L) return "Never"-- val elapsedMs = now - lastSyncTime- val elapsedMinutes = (elapsedMs / 60000).toInt()-- return when {- elapsedMinutes < 1 -> "Just now"- elapsedMinutes == 1 -> "1 min ago"- elapsedMinutes < 60 -> "$elapsedMinutes min ago"- elapsedMinutes < 120 -> "1h ago"- else -> "${elapsedMinutes / 60} h ago"- }- }-- private fun buildStatusText(- isPaused: Boolean,- zoneName: String?,- lat: Double?,- lon: Double?,- queuedCount: Int,- lastSyncTime: Long- ): String {- return when {- isPaused -> "Paused: ${zoneName ?: "Unknown"}"- lat != null && lon != null -> {- val coords = String.format(Locale.US, "%.5f, %.5f", lat, lon)- if (queuedCount > 0 && lastSyncTime > 0) {- "$coords (Last sync: ${formatTimeSinceSync(lastSyncTime, System.currentTimeMillis())})"- } else if (queuedCount > 0) {- "$coords (Queued: $queuedCount)"- } else if (lastSyncTime > 0) {- "$coords (Synced)"- } else {- coords- }- }- else -> "Searching GPS..."- }- }-private fun shouldStopForBattery(battery: Int, batteryStatus: Int): Boolean {return battery in 1..4 && batteryStatus == 1}-- private fun shouldUpdateNotification(lastText: String?, newText: String): Boolean {- return newText != lastText- }-}+}\ No newline at end of filediff --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.ktnew file mode 100644index 00000000..ff2fdb66--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt@@ -0,0 +1,226 @@+package com.Colota.service++import org.junit.Assert.*+import org.junit.Test++/**+ * Tests for NotificationHelper's pure logic:+ * - Status text generation (all branches)+ * - Time-since-last-sync formatting+ * - Throttle decisions+ * - Movement filter decisions+ * - Deduplication+ * - Initial status text+ */+class NotificationHelperTest {++ // --- formatTimeSinceSync ---++ @Test+ fun `time since sync shows Never when no sync happened`() {+ assertEquals("Never", formatTimeSinceSync(lastSyncTime = 0L, now = 1000L))+ }++ @Test+ fun `time since sync shows Just now for less than 1 min`() {+ val now = 100000L+ val lastSync = now - 30000L+ assertEquals("Just now", formatTimeSinceSync(lastSync, now))+ }++ @Test+ fun `time since sync shows 1 min ago`() {+ val now = 100000L+ val lastSync = now - 60000L+ assertEquals("1 min ago", formatTimeSinceSync(lastSync, now))+ }++ @Test+ fun `time since sync shows N min ago for less than 1 hour`() {+ val now = 100000L+ val lastSync = now - 1500000L+ assertEquals("25 min ago", formatTimeSinceSync(lastSync, now))+ }++ @Test+ fun `time since sync shows 1h ago for 60-119 minutes`() {+ val now = 10000000L+ val lastSync = now - 3600000L+ assertEquals("1h ago", formatTimeSinceSync(lastSync, now))+ }++ @Test+ fun `time since sync shows Nh ago for 120+ minutes`() {+ val now = 10000000L+ val lastSync = now - 7200000L+ assertEquals("2 h ago", formatTimeSinceSync(lastSync, now))+ }++ @Test+ fun `time since sync shows 5h ago for 300 minutes`() {+ val now = 100000000L+ val lastSync = now - 18000000L+ assertEquals("5 h ago", formatTimeSinceSync(lastSync, now))+ }++ // --- buildStatusText ---++ @Test+ fun `status text shows Paused with zone name`() {+ val text = buildStatusText(true, "Home", 52.0, 13.0, 0, 0L)+ assertEquals("Paused: Home", text)+ }++ @Test+ fun `status text shows Paused Unknown when zone name is null`() {+ val text = buildStatusText(true, null, 52.0, 13.0, 0, 0L)+ assertEquals("Paused: Unknown", text)+ }++ @Test+ fun `status text shows coordinates when tracking normally`() {+ val text = buildStatusText(false, null, 52.51630, 13.37770, 0, 0L)+ assertEquals("52.51630, 13.37770", text)+ }++ @Test+ fun `status text shows Synced when queue empty and has synced`() {+ val text = buildStatusText(false, null, 52.0, 13.0, 0, System.currentTimeMillis())+ assertEquals("52.00000, 13.00000 (Synced)", text)+ }++ @Test+ fun `status text shows queued count when never synced`() {+ val text = buildStatusText(false, null, 52.0, 13.0, 15, 0L)+ assertEquals("52.00000, 13.00000 (Queued: 15)", text)+ }++ @Test+ fun `status text shows queued count and last sync when both present`() {+ val now = System.currentTimeMillis()+ val text = buildStatusText(false, null, 52.0, 13.0, 7, now - 30000L)+ assertEquals("52.00000, 13.00000 (Queued: 7 · Just now)", text)+ }++ @Test+ fun `status text shows Searching GPS when no coordinates`() {+ val text = buildStatusText(false, null, null, null, 0, 0L)+ assertEquals("Searching GPS...", text)+ }++ @Test+ fun `status text uses locale-safe coordinate formatting`() {+ // Verifies no comma-separated decimals on non-US locales+ val text = buildStatusText(false, null, -33.86882, 151.20930, 0, 0L)+ assertTrue(text.contains("-33.86882"))+ assertTrue(text.contains("151.20930"))+ assertFalse(text.contains(",209")) // Would appear with German locale+ }++ @Test+ fun `paused takes priority over coordinates`() {+ val text = buildStatusText(true, "Office", 52.0, 13.0, 5, System.currentTimeMillis())+ assertEquals("Paused: Office", text)+ }++ // --- shouldThrottle ---++ @Test+ fun `throttle suppresses within 10s`() {+ assertTrue(shouldThrottle(lastUpdateTime = 1000L, now = 5000L))+ }++ @Test+ fun `throttle allows after 10s`() {+ assertFalse(shouldThrottle(lastUpdateTime = 1000L, now = 12000L))+ }++ @Test+ fun `throttle allows at exactly 10s`() {+ assertFalse(shouldThrottle(lastUpdateTime = 1000L, now = 11000L))+ }++ // --- shouldFilterByMovement ---++ @Test+ fun `movement less than 2m is filtered`() {+ assertTrue(shouldFilterByMovement(1.5f))+ }++ @Test+ fun `movement of exactly 2m is not filtered`() {+ assertFalse(shouldFilterByMovement(2.0f))+ }++ @Test+ fun `movement greater than 2m is not filtered`() {+ assertFalse(shouldFilterByMovement(5.0f))+ }++ // --- Deduplication ---++ @Test+ fun `same cache key is deduplicated`() {+ assertFalse(shouldUpdate("52.52000, 13.40500-3", "52.52000, 13.40500-3"))+ }++ @Test+ fun `different cache key is not deduplicated`() {+ assertTrue(shouldUpdate("52.52000, 13.40500-3", "52.52100, 13.40600-3"))+ }++ @Test+ fun `first update always proceeds`() {+ assertTrue(shouldUpdate(null, "52.52000, 13.40500-0"))+ }++ @Test+ fun `queue count change triggers update even if text same`() {+ assertTrue(shouldUpdate("52.00000, 13.00000 (Synced)-0", "52.00000, 13.00000 (Synced)-5"))+ }++ // --- Helper methods that mirror NotificationHelper logic ---++ private fun formatTimeSinceSync(lastSyncTime: Long, now: Long): String {+ if (lastSyncTime == 0L) return "Never"+ val elapsedMs = now - lastSyncTime+ val elapsedMinutes = (elapsedMs / 60000).toInt()+ return when {+ elapsedMinutes < 1 -> "Just now"+ elapsedMinutes == 1 -> "1 min ago"+ elapsedMinutes < 60 -> "$elapsedMinutes min ago"+ elapsedMinutes < 120 -> "1h ago"+ else -> "${elapsedMinutes / 60} h ago"+ }+ }++ private fun buildStatusText(+ isPaused: Boolean, zoneName: String?,+ lat: Double?, lon: Double?,+ queuedCount: Int, lastSyncTime: Long+ ): String = when {+ isPaused -> "Paused: ${zoneName ?: "Unknown"}"+ lat != null && lon != null -> {+ val coords = String.format(java.util.Locale.US, "%.5f, %.5f", lat, lon)+ if (queuedCount > 0 && lastSyncTime > 0) {+ "$coords (Queued: $queuedCount · ${formatTimeSinceSync(lastSyncTime, System.currentTimeMillis())})"+ } else if (queuedCount > 0) {+ "$coords (Queued: $queuedCount)"+ } else if (lastSyncTime > 0) {+ "$coords (Synced)"+ } else {+ coords+ }+ }+ else -> "Searching GPS..."+ }++ private fun shouldThrottle(lastUpdateTime: Long, now: Long): Boolean =+ (now - lastUpdateTime) < NotificationHelper.THROTTLE_MS++ private fun shouldFilterByMovement(distance: Float): Boolean =+ distance < NotificationHelper.MIN_MOVEMENT_METERS++ private fun shouldUpdate(lastText: String?, newText: String): Boolean =+ newText != lastText+}\ No newline at end of file