Skip to content

Colota - Android GPS Location tracker

refactor(notifications): show tracking state and queue instead of coordinates (#842)

Max Dietriche0293ac97617
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.md
index ca75ec2c..b32e300c 100644
--- a/apps/docs/docs/configuration/server-settings.md
+++ b/apps/docs/docs/configuration/server-settings.md
@@ -73,7 +73,7 @@ The UI simplifies to remove sync-related elements that don't apply:
- Sync Interval, Sync Condition (Any / Wi-Fi / SSID / VPN)
- Queue statistics (Queued / Sent counts)
- Queue actions (Sync Now, Clear Sent History, Clear Queue)
-- Queue info in the tracking notification
+- Queue info in the tracking notification, which reads "Offline mode" instead
**Still available in offline mode:**
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index f2554563..43aed2c4 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -171,9 +171,11 @@ the app stays closed.
Handles all notification logic for the tracking service:
- Channel creation and notification building
-- Dynamic title: "Colota Tracking" by default, "Colota · ProfileName" when a tracking profile is active
-- Status text generation (coordinates, sync status, pause zones)
-- Throttled updates (10s minimum interval, 2m minimum movement)
+- Title is the recording state: "Tracking", "Paused", "Searching for GPS" or "Location services are off". From Android 12 the collapsed row shows the app name only when there is no title, so the notification sets none there: the state leads the text and the expanded view shows it as the title. Before Android 12 the state is the title. The stopped notification follows the same rule
+- Text is the sending state ("All sent", "12 queued · last sync 3 min ago", "Offline mode"), after "Stationary", "Not recording" or how a pause resumes where one applies. `NotificationHelper.StatusInput` has no coordinate, zone or profile field and `statusInput()` in the service is its only builder
+- `Notification.when` is the last fix received, so the header age updates without a post. An update posts when the title, the text or the fix minute changes. A state change always posts
+- Both notifications are `VISIBILITY_PUBLIC`, since the text holds nothing private
+- Small icon `drawable/ic_notification`: the launcher's monochrome pin and inner arc at 24 dp, without the outer arc and with the stroke doubled. `setColor(ICON_COLOR)`, the launcher background, colors the circle Android 12 and later draw behind it. `BatteryRecoveryWorker` uses the same icon and color. The stopped notification keeps `ic_lock_power_off` so the status bar icon changes when tracking ends, and backup and auto-export keep `ic_menu_save`
- Deduplication to avoid unnecessary notification redraws
- Stopped notification, posted on a deliberate stop and by the tracking watchdog when Android refuses a background restart, in which case tapping it opens the app so the reconciler can resume. Two channels back it. `location_service_channel` at `IMPORTANCE_LOW` carries the ongoing status and any stop the user asked for; `tracking_stopped_channel` at `IMPORTANCE_DEFAULT` carries the ones they did not, so a killed service is audible instead of sitting silently under the ongoing notification. `buildStoppedNotification` defaults to the silent channel and callers opt in
diff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.md
index c71e8f96..c751335d 100644
--- a/apps/docs/docs/development/local-setup.md
+++ b/apps/docs/docs/development/local-setup.md
@@ -172,7 +172,7 @@ 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
-- **NotificationHelper** - Status text generation, throttling, movement filter, deduplication
+- **NotificationHelper** - Status text generation, header time, deduplication
- **LocationForegroundService** - Battery shutdown, accuracy filtering, zone state machine
- **ServiceConfig** - Database/Intent/ReadableMap parsing, defaults, round-trips
- **PayloadBuilder** - Payload construction (field-mapped, Overland, Traccar) and field map parsing
diff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.md
index ee635165..53263461 100644
--- a/apps/docs/docs/development/permissions.md
+++ b/apps/docs/docs/development/permissions.md
@@ -57,7 +57,7 @@ android.permission.FOREGROUND_SERVICE_LOCATION
android.permission.FOREGROUND_SERVICE_DATA_SYNC
```
-Android requires apps to declare a foreground service with a persistent notification to run in the background. The `FOREGROUND_SERVICE_LOCATION` type specifically indicates the service accesses location data. This is what keeps the "Colota is tracking" notification visible. The `FOREGROUND_SERVICE_DATA_SYNC` type is used by the auto-export WorkManager service for scheduled background exports and by the encrypted backup/restore service for the encryption phase.
+Android requires apps to declare a foreground service with a persistent notification to run in the background. The `FOREGROUND_SERVICE_LOCATION` type specifically indicates the service accesses location data. This is what keeps the tracking notification visible. The `FOREGROUND_SERVICE_DATA_SYNC` type is used by the auto-export WorkManager service for scheduled background exports and by the encrypted backup/restore service for the encryption phase.
### Network
diff --git a/apps/docs/docs/guides/battery-optimization.md b/apps/docs/docs/guides/battery-optimization.md
index 785b7f8b..d1bdf7b0 100644
--- a/apps/docs/docs/guides/battery-optimization.md
+++ b/apps/docs/docs/guides/battery-optimization.md
@@ -9,10 +9,10 @@ Settings and tips to reduce battery usage without losing GPS fixes.
## Built-in Optimizations
- **Stationary detection**: When the device is still, [tracking profiles](/docs/guides/tracking-profiles) drop to a low-frequency heartbeat and [geofence motionless detection](/docs/guides/geofencing) stops GPS entirely; both resume on motion via the hardware sensor
-- **Notification throttling**: Max 1 update per 10 seconds, plus 2-meter movement filter
+- **Notification updates**: redrawn when the status text changes, otherwise at most once a minute while fixes arrive
- **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 & 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
+- **Battery critical shutdown & auto-resume**: Stops tracking below 5% when unplugged (the dashboard shows "Tracking stopped" and a notification reads "Battery fell below 5% · resumes when charging"), 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/geofencing.md b/apps/docs/docs/guides/geofencing.md
index b52070ce..f9ca6b60 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -80,7 +80,7 @@ See the [Deep Link Setup](deep-link-setup.md#geofences) guide for the full paylo
- Zone detection uses the Haversine formula (1-2ms per check)
- When entering a pause zone, Colota keeps recording for 3.5× your tracking interval before pausing - this logs several real arrival points near the zone boundary, which backends like GeoPulse need to confirm a trip has ended. The delay uses your configured interval.
-- The notification shows "Paused: [Zone Name]" once the pause takes effect
+- The notification shows "Paused" with "Inside zone", "Zone WiFi" or "No movement" and when tracking resumes. The zone name only appears on the Dashboard
- By default, GPS continues running inside the zone to detect when you leave. If **WiFi pause** or **motionless pause** is enabled, GPS stops entirely inside the zone and zone exit is detected when GPS resumes
- If you leave before the entry delay completes, the delay is cancelled and tracking continues uninterrupted
- Stationary detection is suspended inside zones so GPS is never stopped by the stationary timer while zone exit needs to be detected
diff --git a/apps/docs/docs/guides/tracking-profiles.md b/apps/docs/docs/guides/tracking-profiles.md
index 926e94c2..4b7c3d2a 100644
--- a/apps/docs/docs/guides/tracking-profiles.md
+++ b/apps/docs/docs/guides/tracking-profiles.md
@@ -104,9 +104,6 @@ Note that Stationary has the highest priority so it takes over from Walking when
## Active Profile Indicators
-When a profile is active, Colota shows it in two places:
+When a profile is active, the Dashboard shows it: an info card on the map names the active profile. When inside a pause zone, the pause card shows which profile will resume on exit (e.g., "Profile 'Charging' resumes on exit").
-- **Notification** - The foreground notification title changes from "Colota Tracking" to "Colota · ProfileName" (e.g., "Colota · Charging")
-- **Dashboard** - An info card appears on the map showing the active profile name. When inside a pause zone, the pause card shows which profile will resume on exit (e.g., "Profile 'Charging' resumes on exit").
-
-Both indicators disappear automatically when the profile deactivates (after the deactivation delay) or when tracking stops.
+The indicator disappears automatically when the profile deactivates (after the deactivation delay) or when tracking stops.
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index 4c11d53b..d7815f53 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -9,8 +9,10 @@ sidebar_position: 4
- Go to **Settings > Apps > Colota > Battery** and select **Unrestricted**
- Verify location permissions are set to **Allow all the time**
- Grant notification permission if you want to see tracking status
+- While tracking runs the status bar shows Colota's pin, the launcher icon's mark, and the notification carries it on a teal disc
- If the notification disappeared while the app still shows tracking on, Android killed the service. Opening the app restarts it. With battery set to **Unrestricted** it also restarts on its own, usually within 15 to 30 minutes
- When Colota cannot restart itself it posts a **Tracking stopped** notification instead, and tapping that resumes tracking. It has its own notification channel, so if you never see it, check that **Tracking stopped** is enabled in Android's notification settings for Colota
+- The time in the notification header is the last position fix Colota received. It keeps counting while a pause keeps GPS off. While you move, it only grows if location updates have stopped
## Tracking doesn't start after reboot
diff --git a/apps/docs/docs/security.md b/apps/docs/docs/security.md
index a4ff7e52..08921783 100644
--- a/apps/docs/docs/security.md
+++ b/apps/docs/docs/security.md
@@ -49,6 +49,10 @@ Colota can produce a single password-encrypted archive of your full dataset (loc
The format is fully documented in [`BackupFormat.kt`](https://github.com/dietrichmax/colota/blob/main/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt).
+## The Tracking Notification
+
+The persistent notification shows whether tracking is recording, paused or searching, how many locations wait to be sent and when the last sync succeeded. It never shows your coordinates, a zone name or a profile name, so apps with notification access, screenshots and screen shares reveal no location. For the same reason it is shown in full on the lock screen. Android's lock-screen settings can still hide it.
+
## What Colota Does Not Do
- No analytics, telemetry or crash reporting
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
index e8e5e298..0a1c37f2 100644
--- 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
@@ -14,6 +14,7 @@ import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
+import com.Colota.R
import com.Colota.data.DatabaseHelper
import com.Colota.data.SettingsKeys
import com.Colota.util.AppLogger
@@ -40,7 +41,8 @@ class BatteryRecoveryWorker(
override suspend fun getForegroundInfo(): ForegroundInfo {
ensureNotificationChannel()
val notification = NotificationCompat.Builder(appContext, CHANNEL_ID)
- .setSmallIcon(android.R.drawable.ic_menu_mylocation)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setColor(NotificationHelper.ICON_COLOR)
.setContentTitle("Resuming tracking")
.setContentText("Charger connected - restarting location tracking")
.setOngoing(true)
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 a4bd571d..2b048228 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
@@ -66,6 +66,8 @@ class LocationForegroundService : Service() {
@Volatile private var trackingHeartbeatJob: Job? = null
@Volatile private var lastFixAtMs: Long = 0L
@Volatile private var lastFixAtUptimeMs: Long = 0L
+ @Volatile private var lastFixEpochMs: Long = 0L
+ private val startedAtMs: Long = System.currentTimeMillis()
@Volatile private var motionDetector: MotionStateDetector? = null
@Volatile private var lastKnownLocation: Location? = null
@@ -335,18 +337,12 @@ class LocationForegroundService : Service() {
}
// Must call startForeground within 5s
- val initialStatus = notificationHelper.getInitialStatus(
- insidePauseZone, currentZoneName, lastKnownLocation
- )
- val initialTitle = notificationHelper.buildTitle(
- if (::profileManager.isInitialized) profileManager.getActiveProfileName() else null
- )
notificationManager.cancel(NotificationHelper.STOPPED_NOTIFICATION_ID)
try {
ServiceCompat.startForeground(
this,
NotificationHelper.NOTIFICATION_ID,
- notificationHelper.buildTrackingNotification(initialTitle, initialStatus),
+ notificationHelper.buildForegroundNotification(statusInput()),
ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION
)
} catch (e: Exception) {
@@ -396,12 +392,7 @@ class LocationForegroundService : Service() {
private fun handleRefreshNotification() {
syncManager.invalidateQueueCache()
- val loc = lastKnownLocation
- updateNotification(
- lat = loc?.latitude,
- lon = loc?.longitude,
- forceUpdate = true
- )
+ updateNotification(forceUpdate = true)
}
private fun handleRecheckProfiles() {
@@ -521,7 +512,7 @@ class LocationForegroundService : Service() {
if (deviceInfoHelper.isBatteryCritical()) {
val (level, _) = deviceInfoHelper.getCachedBatteryStatus()
AppLogger.d(TAG, "Battery critical ($level%) and unplugged - stopping service")
- stopForegroundServiceWithReason("Battery below 5% - tracking paused", stoppedByBattery = true)
+ stopForegroundServiceWithReason(NotificationHelper.STOP_REASON_BATTERY, stoppedByBattery = true)
return
}
@@ -559,7 +550,7 @@ class LocationForegroundService : Service() {
geofenceHelper.getPauseZone(location)?.let { zone ->
enterPauseZone(zone)
} ?: run {
- updateNotification(location.latitude, location.longitude, forceUpdate = true)
+ updateNotification(forceUpdate = true)
}
}
},
@@ -822,11 +813,7 @@ class LocationForegroundService : Service() {
// Already inside this zone - refresh settings in case they changed via editor
if (zone != null && insidePauseZone && zone.name == currentZoneName) {
applyZoneSettingsIfChanged(zone)
- updateNotification(
- lat = location.latitude,
- lon = location.longitude,
- forceUpdate = true
- )
+ updateNotification(forceUpdate = true)
val reason = when {
isWifiPaused -> "wifi"
isMotionlessPaused -> "motionless"
@@ -839,11 +826,7 @@ class LocationForegroundService : Service() {
applyZoneTransition(zone)
if (zone == null && !insidePauseZone && pendingPauseZone == null) {
- updateNotification(
- location.latitude,
- location.longitude,
- forceUpdate = true
- )
+ updateNotification(forceUpdate = true)
}
}
@@ -922,6 +905,9 @@ class LocationForegroundService : Service() {
}
private fun handleLocationUpdate(location: Location) {
+ // Stamped before the filters: the header time is the last fix received, saved or not.
+ lastFixEpochMs = location.time
+ updateNotification()
if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {
AppLogger.d(TAG, "Location filtered: accuracy ${location.accuracy}m > threshold ${config.accuracyThreshold}m")
return
@@ -1008,9 +994,7 @@ class LocationForegroundService : Service() {
syncManager.queueAndSend(locationId, payload)
- withContext(Dispatchers.Main) {
- updateNotification(location.latitude, location.longitude)
- }
+ withContext(Dispatchers.Main) { updateNotification() }
}
}
@@ -1423,47 +1407,35 @@ class LocationForegroundService : Service() {
}
}
- /**
- * Forces a notification refresh using the current pause/zone state and last known location.
- * Call after any pause-state change (enter/exit zone, wifi/motionless activate/clear, profile swap).
- *
- * Contract: this reads [insidePauseZone], [currentZoneName], and [lastKnownLocation] directly.
- * Callers MUST mutate those fields (and persist pause-state settings when relevant)
- * BEFORE invoking this — order is state → DB → refresh. Refreshing before the state
- * is written will render a stale notification.
- */
+ /** Call once the pause-state fields and settings are written, or it posts the old state. */
private fun refreshNotificationForCurrentState() {
- val loc = lastKnownLocation
- updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
+ updateNotification(forceUpdate = true)
}
- private fun updateNotification(
- lat: Double? = null,
- lon: Double? = null,
- forceUpdate: Boolean = false
- ) {
+ private fun updateNotification(forceUpdate: Boolean = false) {
+ notificationHelper.update(statusInput(), forceUpdate)
+ }
+
+ private fun statusInput(): NotificationHelper.StatusInput {
val offline = ::config.isInitialized && config.isOfflineMode
- notificationHelper.update(
- lat = lat,
- lon = lon,
+ return NotificationHelper.StatusInput(
+ locationEnabled = deviceInfoHelper.isLocationEnabled(),
isPaused = insidePauseZone,
- zoneName = currentZoneName,
- queuedCount = if (offline) 0 else syncManager.getCachedQueuedCount(),
- lastSyncTime = if (offline) 0L else syncManager.lastSuccessfulSyncTime,
- activeProfileName = profileManager.getActiveProfileName(),
- forceUpdate = forceUpdate,
- isOfflineMode = offline,
- isStationary = profileManager.isStationary,
isWifiPaused = isWifiPaused,
isMotionlessPaused = isMotionlessPaused,
- locationEnabled = deviceInfoHelper.isLocationEnabled()
+ isStationary = ::profileManager.isInitialized && profileManager.isStationary,
+ hasFix = lastKnownLocation != null,
+ lastFixMs = lastFixEpochMs.takeIf { it > 0L } ?: startedAtMs,
+ isOfflineMode = offline,
+ queuedCount = if (offline) 0 else syncManager.getCachedQueuedCount(),
+ lastSyncTime = if (offline) 0L else syncManager.lastSuccessfulSyncTime
)
}
/** Fired by [batteryMonitor] on a critical-battery broadcast. */
private fun onBatteryCritical() {
AppLogger.i(TAG, "Battery critical and unplugged - stopping (battery monitor)")
- stopForegroundServiceWithReason("Battery below 5% - tracking paused", stoppedByBattery = true)
+ stopForegroundServiceWithReason(NotificationHelper.STOP_REASON_BATTERY, stoppedByBattery = true)
}
private fun stopForegroundServiceWithReason(
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 0b3221f4..a7d9c4c0 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
@@ -8,9 +8,10 @@ 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
+import com.Colota.R
/**
* Main-thread only. All callers run on Main (onStartCommand, FLP callback,
@@ -22,18 +23,35 @@ class NotificationHelper(
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
+ /** No coordinate, zone or profile field on purpose: the notification is public. */
+ data class StatusInput(
+ val locationEnabled: Boolean = true,
+ val isPaused: Boolean = false,
+ val isWifiPaused: Boolean = false,
+ val isMotionlessPaused: Boolean = false,
+ val isStationary: Boolean = false,
+ val hasFix: Boolean = false,
+ val lastFixMs: Long,
+ val isOfflineMode: Boolean = false,
+ val queuedCount: Int = 0,
+ val lastSyncTime: Long = 0L
+ )
+
+ data class Status(val title: String, val text: String)
+
+ private var lastKey: String? = null
+
+ /** From Android 12 the collapsed row shows the app name only when there is no title. */
+ private val headerless = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
companion object {
const val CHANNEL_ID = "location_service_channel"
const val STOPPED_CHANNEL_ID = "tracking_stopped_channel"
const val NOTIFICATION_ID = 1
const val STOPPED_NOTIFICATION_ID = 2
- const val THROTTLE_MS = 10000L
- const val MIN_MOVEMENT_METERS = 2f
+ const val STOP_REASON_BATTERY = "Battery fell below 5% · resumes when charging"
+ /** ic_launcher_background, copied because unit tests run without app resources. */
+ const val ICON_COLOR = 0xFF0D9387.toInt()
}
fun createChannel() {
@@ -58,7 +76,7 @@ class NotificationHelper(
notificationManager.createNotificationChannel(stoppedChannel)
}
- fun buildTrackingNotification(title: String, statusText: String): Notification {
+ fun buildTrackingNotification(status: Status, whenMs: Long): Notification {
val pendingIntent = PendingIntent.getActivity(
context,
0,
@@ -67,19 +85,21 @@ class NotificationHelper(
)
return NotificationCompat.Builder(context, CHANNEL_ID)
- .setContentTitle(title)
- .setContentText(statusText)
- .setSmallIcon(android.R.drawable.ic_menu_mylocation)
+ .setContentTitle(collapsedTitle(status.title))
+ .setContentText(collapsedText(status.title, status.text))
+ .setStyle(NotificationCompat.BigTextStyle().setBigContentTitle(status.title).bigText(status.text))
+ .setSmallIcon(R.drawable.ic_notification)
+ .setColor(ICON_COLOR)
.setOngoing(true)
.setSilent(true)
+ .setWhen(whenMs)
+ .setShowWhen(true)
+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
}
- fun buildTitle(activeProfileName: String?): String =
- if (activeProfileName != null) "Colota \u00b7 $activeProfileName" else "Colota Tracking"
-
/**
* @param unexpected a stop the user did not ask for, which alerts. Anything else stays on the
* silent tracking channel, so a caller has to opt in rather than inherit the alert.
@@ -98,8 +118,9 @@ class NotificationHelper(
context,
if (unexpected) STOPPED_CHANNEL_ID else CHANNEL_ID
)
- .setContentTitle("Tracking stopped")
- .setContentText(reason)
+ .setContentTitle(collapsedTitle("Tracking stopped"))
+ .setContentText(collapsedText("Tracking stopped", reason))
+ .setStyle(NotificationCompat.BigTextStyle().setBigContentTitle("Tracking stopped").bigText(reason))
.setSmallIcon(android.R.drawable.ic_lock_power_off)
.setOngoing(false)
.setAutoCancel(true)
@@ -107,134 +128,71 @@ class NotificationHelper(
// starts a fresh post, which alerts again: tracking is still down and a tap is the fix.
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build()
}
- /** Status text for the initial startForeground notification, before any location arrives. */
- fun getInitialStatus(
- insidePauseZone: Boolean,
- currentZoneName: String?,
- lastKnownLocation: android.location.Location?
- ): String = when {
- insidePauseZone -> "Paused: ${currentZoneName ?: "Unknown"}"
- lastKnownLocation != null -> formatCoords(lastKnownLocation.latitude, lastKnownLocation.longitude)
- else -> "Searching GPS..."
- }
+ private fun collapsedTitle(state: String): String? = if (headerless) null else state
- private fun formatCoords(lat: Double, lon: Double): String =
- String.format(Locale.US, "%.5f, %.5f", lat, lon)
-
- fun buildStatusText(
- isPaused: Boolean,
- zoneName: String?,
- lat: Double?,
- lon: Double?,
- queuedCount: Int,
- lastSyncTime: Long,
- isOfflineMode: Boolean = false,
- isStationary: Boolean = false,
- isWifiPaused: Boolean = false,
- isMotionlessPaused: Boolean = false,
- locationEnabled: Boolean = true
- ): String = when {
- !locationEnabled -> "Location services off - tracking won't get fixes"
- isPaused -> {
- val zone = zoneName ?: "Unknown"
- when {
- isWifiPaused -> "Paused: $zone \u00b7 WiFi"
- isMotionlessPaused -> "Paused: $zone \u00b7 Motionless"
- else -> "Paused: $zone"
- }
- }
- isStationary -> {
- val coords = if (lat != null && lon != null) formatCoords(lat, lon) else ""
- if (coords.isNotEmpty()) "Stationary - $coords" else "Stationary - GPS paused"
- }
- lat != null && lon != null -> {
- val coords = formatCoords(lat, lon)
- if (isOfflineMode) {
- coords
- } else 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
- }
+ private fun collapsedText(state: String, text: String): String = if (headerless) "$state · $text" else text
+
+ /** Title is the recording state, text the sending state. */
+ fun buildStatus(input: StatusInput, now: Long = System.currentTimeMillis()): Status {
+ val send = sendSegment(input, now)
+ return when {
+ !input.locationEnabled -> Status("Location services are off", "Not recording · $send")
+ input.isPaused -> Status("Paused", "${pauseDetail(input)} · $send")
+ !input.hasFix -> Status("Searching for GPS", send)
+ input.isStationary -> Status("Tracking", "Stationary · $send")
+ else -> Status("Tracking", send)
}
- else -> "Searching GPS..."
}
- fun formatTimeSinceSync(lastSyncTime: Long, now: Long = System.currentTimeMillis()): String {
- if (lastSyncTime == 0L) return "Never"
+ private fun pauseDetail(input: StatusInput): String = when {
+ input.isWifiPaused -> "Zone WiFi · resumes when you leave"
+ input.isMotionlessPaused -> "No movement · resumes when you move"
+ else -> "Inside zone · resumes when you leave"
+ }
- val elapsedMs = now - lastSyncTime
- val elapsedMinutes = (elapsedMs / 60000).toInt()
+ private fun sendSegment(input: StatusInput, now: Long): String = when {
+ input.isOfflineMode -> "Offline mode"
+ input.queuedCount > 0 && input.lastSyncTime > 0 ->
+ "${input.queuedCount} queued · last sync ${formatTimeSinceSync(input.lastSyncTime, now)}"
+ input.queuedCount > 0 -> "${input.queuedCount} queued"
+ else -> "All sent"
+ }
+ fun formatTimeSinceSync(lastSyncTime: Long, now: Long): String {
+ val minutes = ((now - lastSyncTime) / 60_000).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"
+ minutes < 1 -> "just now"
+ minutes == 1 -> "1 min ago"
+ minutes < 60 -> "$minutes min ago"
+ minutes < 120 -> "1 h ago"
+ minutes < 1440 -> "${minutes / 60} h ago"
+ minutes < 2880 -> "1 d ago"
+ else -> "${minutes / 1440} d ago"
}
}
- fun shouldThrottle(now: Long): Boolean = (now - lastUpdateTime) < THROTTLE_MS
-
- fun shouldFilterByMovement(distanceMeters: Float): Boolean = distanceMeters < MIN_MOVEMENT_METERS
-
- /** Runs throttle + movement filter + dedup. Returns true if the notification was posted. */
- fun update(
- lat: Double? = null,
- lon: Double? = null,
- isPaused: Boolean = false,
- zoneName: String? = null,
- queuedCount: Int = 0,
- lastSyncTime: Long = 0L,
- activeProfileName: String? = null,
- forceUpdate: Boolean = false,
- isOfflineMode: Boolean = false,
- isStationary: Boolean = false,
- isWifiPaused: Boolean = false,
- isMotionlessPaused: Boolean = false,
- locationEnabled: Boolean = true
- ): Boolean {
- val now = System.currentTimeMillis()
-
- val queueCountChanged = queuedCount != lastQueuedCount
-
- // Bypass throttle/movement filter when queue count changed, so queue status 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, isOfflineMode, isStationary, isWifiPaused, isMotionlessPaused, locationEnabled)
+ // The fix minute is part of the key so the header age is at most a minute behind.
+ private fun dedupKey(status: Status, input: StatusInput): String =
+ "${status.title}\n${status.text}\n${input.lastFixMs / 60_000}"
- // forceUpdate bypasses dedup so state-change posts land even when the text is unchanged.
- val cacheKey = "$statusText-$queuedCount-$activeProfileName"
- if (!forceUpdate && cacheKey == lastText) return false
+ /** Also primes the dedup key, so the first update() does not re-post the same state. */
+ fun buildForegroundNotification(input: StatusInput): Notification {
+ val status = buildStatus(input)
+ lastKey = dedupKey(status, input)
+ return buildTrackingNotification(status, input.lastFixMs)
+ }
- lastText = cacheKey
- lastQueuedCount = queuedCount
- val title = buildTitle(activeProfileName)
- notificationManager.notify(NOTIFICATION_ID, buildTrackingNotification(title, statusText))
+ /** Returns true if it posted. forceUpdate skips the dedup check. */
+ fun update(input: StatusInput, forceUpdate: Boolean = false): Boolean {
+ val status = buildStatus(input)
+ val key = dedupKey(status, input)
+ if (!forceUpdate && key == lastKey) return false
+ lastKey = key
+ notificationManager.notify(NOTIFICATION_ID, buildTrackingNotification(status, input.lastFixMs))
return true
}
}
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 694d5082..81ab27f1 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
@@ -116,7 +116,7 @@ class LocationBootReceiver : BroadcastReceiver() {
// Re-announced after a reboot, but the user still has tracking off
// without asking for it, so it alerts like the original stop did.
notificationHelper.buildStoppedNotification(
- "Battery below 5% - tracking paused",
+ NotificationHelper.STOP_REASON_BATTERY,
unexpected = true
)
)
diff --git a/apps/mobile/android/app/src/main/res/drawable/ic_notification.xml b/apps/mobile/android/app/src/main/res/drawable/ic_notification.xml
new file mode 100644
index 00000000..43024adf
--- /dev/null
+++ b/apps/mobile/android/app/src/main/res/drawable/ic_notification.xml
@@ -0,0 +1,23 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <!-- Paths from ic_launcher_monochrome.xml without the outer arc, stroke doubled to hold at 24 dp. -->
+ <group
+ android:scaleX="0.0625"
+ android:scaleY="0.0625"
+ android:translateX="-6.5"
+ android:translateY="-2.5">
+ <path
+ android:pathData="M256,120C196,120 152,164 152,224C152,300 256,392 256,392C256,392 360,300 360,224C360,164 316,120 256,120Z M220,224A36,36 0,1,1 292,224A36,36 0,1,1 220,224Z"
+ android:fillColor="#FFFFFFFF"
+ android:fillType="evenOdd"/>
+ <path
+ android:pathData="M256,88a168,168 0,0 1,168 168"
+ android:strokeWidth="32"
+ android:fillColor="#00000000"
+ android:strokeColor="#FFFFFFFF"
+ android:strokeLineCap="round"/>
+ </group>
+</vector>
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
index 14129f8a..80402bc0 100644
--- 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
@@ -11,6 +11,7 @@ import android.os.BatteryManager
import androidx.test.core.app.ApplicationProvider
import androidx.work.ListenableWorker
import androidx.work.testing.TestListenableWorkerBuilder
+import com.Colota.R
import com.Colota.bridge.LocationServiceModule
import com.Colota.data.DatabaseHelper
import com.Colota.data.SettingsKeys
@@ -58,6 +59,14 @@ class BatteryRecoveryWorkerTest {
unmockkObject(LocationServiceModule)
}
+ @Test
+ fun `the recovery notification uses the tracking icon and color`() {
+ val n = runBlocking { TestListenableWorkerBuilder<BatteryRecoveryWorker>(app).build().getForegroundInfo().notification }
+
+ assertEquals(R.drawable.ic_notification, n.smallIcon.resId)
+ assertEquals(NotificationHelper.ICON_COLOR, n.color)
+ }
+
@Test
fun `resumes the location service when stopped by battery and not tracking`() {
db.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, "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.kt
index aa525bf6..72662e13 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
@@ -1285,6 +1285,37 @@ class LocationForegroundServiceTest {
assertFalse("a sub-min-distance departure must still exit while paused", getField("insidePauseZone"))
}
+ @Test
+ fun `a fix the distance filter drops still refreshes the notification with its time`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 5000L,
+ minUpdateDistance = 50f,
+ accuracyThreshold = 50f,
+ filterInaccurateLocations = true,
+ syncIntervalSeconds = 0
+ ))
+ setField("lastKnownLocation", mockLocation(lat = 52.0, lon = 13.0, time = 1_000_000L, distanceTo = 5f))
+
+ invokeHandleLocationUpdate(mockLocation(lat = 52.00004, lon = 13.0, time = 1_020_000L))
+
+ verify { notificationHelper.update(match { it.hasFix && it.lastFixMs == 1_020_000L }, false) }
+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `the first accepted fix flips Searching for GPS to Tracking after the save`() = testScope.runTest {
+ setField("lastKnownLocation", null)
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+
+ invokeHandleLocationUpdate(mockLocation())
+
+ verifyOrder {
+ notificationHelper.update(match { !it.hasFix }, false)
+ notificationHelper.update(match { it.hasFix }, false)
+ }
+ }
+
// =========================================================================
// enterPauseZone / exitPauseZone state transitions
// =========================================================================
@@ -1330,16 +1361,7 @@ class LocationForegroundServiceTest {
invokeEnterPauseZone(officeGeofence)
- verify { notificationHelper.update(
- lat = 52.0,
- lon = 13.0,
- isPaused = true,
- zoneName = "Office",
- queuedCount = any(),
- lastSyncTime = any(),
- activeProfileName = any(),
- forceUpdate = true
- ) }
+ verify { notificationHelper.update(match { it.isPaused && it.hasFix }, forceUpdate = true) }
}
@Test
@@ -1348,16 +1370,7 @@ class LocationForegroundServiceTest {
invokeEnterPauseZone(homeGeofence)
- verify { notificationHelper.update(
- lat = null,
- lon = null,
- isPaused = true,
- zoneName = "Home",
- queuedCount = any(),
- lastSyncTime = any(),
- activeProfileName = any(),
- forceUpdate = true
- ) }
+ verify { notificationHelper.update(match { it.isPaused && !it.hasFix }, forceUpdate = true) }
}
@Test
@@ -1444,16 +1457,7 @@ class LocationForegroundServiceTest {
invokeExitPauseZone()
- verify { notificationHelper.update(
- lat = 52.0,
- lon = 13.0,
- isPaused = false,
- zoneName = null,
- queuedCount = any(),
- lastSyncTime = any(),
- activeProfileName = any(),
- forceUpdate = true
- ) }
+ verify { notificationHelper.update(match { !it.isPaused }, forceUpdate = true) }
}
@Test
@@ -1561,16 +1565,7 @@ class LocationForegroundServiceTest {
invokeRecheckZoneWithLocation(location)
- verify { notificationHelper.update(
- lat = 52.0,
- lon = 13.0,
- isPaused = true,
- zoneName = "Home",
- queuedCount = any(),
- lastSyncTime = any(),
- activeProfileName = any(),
- forceUpdate = true
- ) }
+ verify { notificationHelper.update(match { it.isPaused }, forceUpdate = true) }
verify { LocationServiceModule.sendPauseZoneEvent(true, "Home", null) }
}
@@ -1630,16 +1625,7 @@ class LocationForegroundServiceTest {
invokeRecheckZoneWithLocation(location)
- verify { notificationHelper.update(
- lat = 52.0,
- lon = 13.0,
- isPaused = false,
- zoneName = null,
- queuedCount = any(),
- lastSyncTime = any(),
- activeProfileName = any(),
- forceUpdate = true
- ) }
+ verify { notificationHelper.update(match { !it.isPaused }, forceUpdate = true) }
}
// =========================================================================
@@ -1709,16 +1695,7 @@ class LocationForegroundServiceTest {
invokeCancelEntryDelay()
- verify { notificationHelper.update(
- lat = 52.0,
- lon = 13.0,
- isPaused = false,
- zoneName = null,
- queuedCount = any(),
- lastSyncTime = any(),
- activeProfileName = any(),
- forceUpdate = true
- ) }
+ verify { notificationHelper.update(match { !it.isPaused }, forceUpdate = true) }
}
@Test
@@ -1869,7 +1846,7 @@ class LocationForegroundServiceTest {
fun `applyProfileConfig forces notification update`() {
invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)
- verify { notificationHelper.update(any(), any(), any(), any(), any(), any(), any(), forceUpdate = true) }
+ verify { notificationHelper.update(any(), forceUpdate = true) }
}
@Test
@@ -2249,7 +2226,7 @@ class LocationForegroundServiceTest {
fun `stopForBattery sends tracking stopped event`() {
invokeOnBatteryCritical()
- verify { LocationServiceModule.sendTrackingStoppedEvent("Battery below 5% - tracking paused") }
+ verify { LocationServiceModule.sendTrackingStoppedEvent("Battery fell below 5% \u00b7 resumes when charging") }
}
@Test
@@ -3449,9 +3426,7 @@ class LocationForegroundServiceTest {
private fun makeCold() {
setField("config", null)
every { dbHelper.getAllSettings() } returns mapOf(SettingsKeys.TRACKING_ENABLED to "true")
- every { notificationHelper.getInitialStatus(any(), any(), any()) } returns "status"
- every { notificationHelper.buildTitle(any()) } returns "Colota Tracking"
- every { notificationHelper.buildTrackingNotification(any(), any()) } returns mockk(relaxed = true)
+ every { notificationHelper.buildForegroundNotification(any()) } returns mockk(relaxed = true)
every { service.startForeground(any<Int>(), any(), any<Int>()) } returns Unit
}
@@ -3465,6 +3440,17 @@ class LocationForegroundServiceTest {
every { extras } returns null
}
+ @Test
+ fun `onStartCommand builds the foreground notification from the service status`() = runServiceTest {
+ makeCold()
+ every { syncManager.getCachedQueuedCount() } returns 7
+
+ service.onStartCommand(intentFor(null), 0, 1)
+ advanceUntilIdle()
+
+ verify { notificationHelper.buildForegroundNotification(match { it.queuedCount == 7 }) }
+ }
+
/** Without this, the tracking notification sits over a service that records nothing. */
@Test
fun `a lightweight wake on a cold service starts tracking in full`() = runServiceTest {
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
index 54b33d89..1796ce62 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
@@ -1,28 +1,55 @@
package com.Colota.service
+import android.app.Notification
+import android.app.NotificationManager
+import com.Colota.R
import io.mockk.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
/**
* Tests for NotificationHelper using a real instance with mocked Android deps:
- * - Status text generation (all branches)
+ * - Status building
* - Time-since-last-sync formatting
- * - Throttle decisions
- * - Movement filter decisions
- * - Title building
- * - Deduplication via update()
+ * - Deduplication
+ * - Posted notification fields (Robolectric)
*/
class NotificationHelperTest {
+ companion object {
+ const val FIX = 1_700_000_000_000L
+ const val NOW = FIX + 600_000L
+
+ fun input(
+ locationEnabled: Boolean = true,
+ isPaused: Boolean = false,
+ isWifiPaused: Boolean = false,
+ isMotionlessPaused: Boolean = false,
+ isStationary: Boolean = false,
+ hasFix: Boolean = false,
+ lastFixMs: Long = FIX,
+ isOfflineMode: Boolean = false,
+ queuedCount: Int = 0,
+ lastSyncTime: Long = 0L
+ ) = NotificationHelper.StatusInput(
+ locationEnabled, isPaused, isWifiPaused, isMotionlessPaused, isStationary,
+ hasFix, lastFixMs, isOfflineMode, queuedCount, lastSyncTime
+ )
+ }
+
// --- channel routing (Robolectric: a real Notification, so the channel can be read back) ---
- @org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
+ @RunWith(RobolectricTestRunner::class)
class ChannelRouting {
- private fun helperFor(): Pair<NotificationHelper, android.app.NotificationManager> {
- val ctx = org.robolectric.RuntimeEnvironment.getApplication()
- val nm = ctx.getSystemService(android.app.NotificationManager::class.java)
+ private fun helperFor(): Pair<NotificationHelper, NotificationManager> {
+ val ctx = RuntimeEnvironment.getApplication()
+ val nm = ctx.getSystemService(NotificationManager::class.java)
return NotificationHelper(ctx, nm) to nm
}
@@ -54,8 +81,124 @@ class NotificationHelperTest {
val tracking = nm.getNotificationChannel(NotificationHelper.CHANNEL_ID)
val stopped = nm.getNotificationChannel(NotificationHelper.STOPPED_CHANNEL_ID)
- assertEquals(android.app.NotificationManager.IMPORTANCE_LOW, tracking.importance)
- assertEquals(android.app.NotificationManager.IMPORTANCE_DEFAULT, stopped.importance)
+ assertEquals(NotificationManager.IMPORTANCE_LOW, tracking.importance)
+ assertEquals(NotificationManager.IMPORTANCE_DEFAULT, stopped.importance)
+ }
+ }
+
+ // --- posted notification (Robolectric) ---
+
+ @RunWith(RobolectricTestRunner::class)
+ class TrackingNotification {
+ private lateinit var helper: NotificationHelper
+ private lateinit var nm: NotificationManager
+
+ @Before
+ fun setUp() {
+ val ctx = RuntimeEnvironment.getApplication()
+ nm = ctx.getSystemService(NotificationManager::class.java)
+ helper = NotificationHelper(ctx, nm)
+ helper.createChannel()
+ }
+
+ private fun posted(): Notification = shadowOf(nm).getNotification(NotificationHelper.NOTIFICATION_ID)
+
+ @Test
+ fun `what is posted is the status that was built`() {
+ helper.update(input(hasFix = true, queuedCount = 2))
+
+ val n = posted()
+ assertNull(n.extras.getString(Notification.EXTRA_TITLE))
+ assertEquals("Tracking · 2 queued", n.extras.getString(Notification.EXTRA_TEXT))
+ assertEquals("Tracking", n.extras.getString(Notification.EXTRA_TITLE_BIG))
+ assertEquals("2 queued", n.extras.getString(Notification.EXTRA_BIG_TEXT))
+ }
+
+ @Test
+ fun `from Android 12 there is no title and the state leads the text`() {
+ helper.update(input(isPaused = true, isWifiPaused = true, hasFix = true))
+
+ val n = posted()
+ assertNull(n.extras.getString(Notification.EXTRA_TITLE))
+ assertEquals("Paused · Zone WiFi · resumes when you leave · All sent", n.extras.getString(Notification.EXTRA_TEXT))
+ assertEquals("Paused", n.extras.getString(Notification.EXTRA_TITLE_BIG))
+ assertEquals("Zone WiFi · resumes when you leave · All sent", n.extras.getString(Notification.EXTRA_BIG_TEXT))
+ }
+
+ @Test
+ @Config(sdk = [30])
+ fun `before Android 12 the state is the title`() {
+ helper.update(input(isPaused = true, isWifiPaused = true, hasFix = true))
+
+ val n = posted()
+ assertEquals("Paused", n.extras.getString(Notification.EXTRA_TITLE))
+ assertEquals("Zone WiFi · resumes when you leave · All sent", n.extras.getString(Notification.EXTRA_TEXT))
+ }
+
+ @Test
+ fun `the stopped notification keeps the full reason in the expanded view`() {
+ val n = helper.buildStoppedNotification("killed", unexpected = true)
+
+ assertNull(n.extras.getString(Notification.EXTRA_TITLE))
+ assertEquals("Tracking stopped · killed", n.extras.getString(Notification.EXTRA_TEXT))
+ assertEquals("Tracking stopped", n.extras.getString(Notification.EXTRA_TITLE_BIG))
+ assertEquals("killed", n.extras.getString(Notification.EXTRA_BIG_TEXT))
+ }
+
+ @Test
+ fun `the small icon is ic_notification`() {
+ helper.update(input(hasFix = true))
+
+ assertEquals(R.drawable.ic_notification, posted().smallIcon.resId)
+ }
+
+ @Test
+ fun `the icon color is the launcher background`() {
+ helper.update(input(hasFix = true))
+
+ assertEquals(0xFF0D9387.toInt(), posted().color)
+ }
+
+ @Test
+ fun `the header time is the last fix received`() {
+ val s = input(hasFix = true, lastFixMs = FIX)
+ helper.update(s)
+
+ val n = posted()
+ assertEquals(FIX, n.`when`)
+ assertTrue(n.extras.getBoolean(Notification.EXTRA_SHOW_WHEN))
+ }
+
+ @Test
+ fun `the tracking notification is public`() {
+ helper.update(input(hasFix = true))
+
+ val n = posted()
+ assertEquals(Notification.VISIBILITY_PUBLIC, n.visibility)
+ assertNull(n.publicVersion)
+ }
+
+ @Test
+ fun `the stopped notification is public`() {
+ assertEquals(Notification.VISIBILITY_PUBLIC, helper.buildStoppedNotification("killed", unexpected = true).visibility)
+ assertEquals(Notification.VISIBILITY_PUBLIC, helper.buildStoppedNotification("stopped", unexpected = false).visibility)
+ }
+
+ @Test
+ fun `the tracking notification is ongoing and silent on the tracking channel`() {
+ helper.update(input(hasFix = true))
+
+ val n = posted()
+ assertTrue(n.flags and Notification.FLAG_ONGOING_EVENT != 0)
+ assertEquals(NotificationHelper.CHANNEL_ID, n.channelId)
+ }
+
+ @Test
+ fun `the foreground notification carries the same facts as an update`() {
+ val n = helper.buildForegroundNotification(input(isStationary = true, hasFix = true, queuedCount = 3))
+
+ assertEquals("Tracking · Stationary · 3 queued", n.extras.getString(Notification.EXTRA_TEXT))
+ assertEquals("Stationary · 3 queued", n.extras.getString(Notification.EXTRA_BIG_TEXT))
}
}
@@ -70,288 +213,189 @@ class NotificationHelperTest {
every { helper.buildTrackingNotification(any(), any()) } returns mockk()
}
- // --- formatTimeSinceSync ---
-
- @Test
- fun `time since sync shows Never when no sync happened`() {
- assertEquals("Never", helper.formatTimeSinceSync(lastSyncTime = 0L, now = 1000L))
- }
-
- @Test
- fun `time since sync shows Just now for less than 1 min`() {
- val now = 100000L
- assertEquals("Just now", helper.formatTimeSinceSync(now - 30000L, now))
- }
+ private fun status(s: NotificationHelper.StatusInput) = helper.buildStatus(s, NOW)
- @Test
- fun `time since sync shows 1 min ago`() {
- val now = 100000L
- assertEquals("1 min ago", helper.formatTimeSinceSync(now - 60000L, now))
- }
+ // --- buildStatus ---
@Test
- fun `time since sync shows N min ago for less than 1 hour`() {
- val now = 100000L
- assertEquals("25 min ago", helper.formatTimeSinceSync(now - 1500000L, now))
+ fun `a fix reads Tracking with the sending state and nothing about where it was`() {
+ assertEquals(NotificationHelper.Status("Tracking", "All sent"), status(input(hasFix = true)))
}
@Test
- fun `time since sync shows 1h ago for 60-119 minutes`() {
- val now = 10000000L
- assertEquals("1h ago", helper.formatTimeSinceSync(now - 3600000L, now))
+ fun `a backed-up queue after a sync this run prints depth and age`() {
+ assertEquals(
+ "12 queued · last sync 3 min ago",
+ status(input(hasFix = true, queuedCount = 12, lastSyncTime = NOW - 180_000L)).text
+ )
}
@Test
- fun `time since sync shows Nh ago for 120+ minutes`() {
- val now = 10000000L
- assertEquals("2 h ago", helper.formatTimeSinceSync(now - 7200000L, now))
+ fun `a backed-up queue with no sync this run prints the depth alone`() {
+ assertEquals("12 queued", status(input(hasFix = true, queuedCount = 12)).text)
}
@Test
- fun `time since sync shows 5h ago for 300 minutes`() {
- val now = 100000000L
- assertEquals("5 h ago", helper.formatTimeSinceSync(now - 18000000L, now))
+ fun `an empty queue reads All sent regardless of the last sync time`() {
+ assertEquals("All sent", status(input(hasFix = true, lastSyncTime = 0L)).text)
+ assertEquals("All sent", status(input(hasFix = true, lastSyncTime = NOW - 60_000L)).text)
}
- // --- buildStatusText ---
-
@Test
- fun `status text shows Paused with zone name`() {
- assertEquals("Paused: Home", helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L))
+ fun `offline mode replaces every queue fact`() {
+ assertEquals(
+ "Offline mode",
+ status(input(hasFix = true, isOfflineMode = true, queuedCount = 12, lastSyncTime = NOW - 60_000L)).text
+ )
}
@Test
- fun `status text shows Paused Unknown when zone name is null`() {
- assertEquals("Paused: Unknown", helper.buildStatusText(true, null, 52.0, 13.0, 0, 0L))
+ fun `no fix reads Searching for GPS over the sending state`() {
+ assertEquals(NotificationHelper.Status("Searching for GPS", "3 queued"), status(input(hasFix = false, queuedCount = 3)))
}
@Test
- fun `status text shows WiFi suffix when wifi paused`() {
+ fun `location services off takes precedence over pause and stationary`() {
assertEquals(
- "Paused: Home \u00b7 WiFi",
- helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, isWifiPaused = true)
+ NotificationHelper.Status("Location services are off", "Not recording · All sent"),
+ status(input(locationEnabled = false, isPaused = true, isStationary = true, hasFix = true))
)
}
@Test
- fun `status text shows Motionless suffix when motionless paused`() {
+ fun `a zone pause shows how it resumes without the zone name`() {
assertEquals(
- "Paused: Home \u00b7 Motionless",
- helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, isMotionlessPaused = true)
+ NotificationHelper.Status("Paused", "Inside zone · resumes when you leave · All sent"),
+ status(input(isPaused = true, hasFix = true))
)
}
@Test
- fun `status text WiFi takes priority over motionless when both active`() {
+ fun `a WiFi hold names the WiFi as the reason`() {
assertEquals(
- "Paused: Home \u00b7 WiFi",
- helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, isWifiPaused = true, isMotionlessPaused = true)
+ "Zone WiFi · resumes when you leave · All sent",
+ status(input(isPaused = true, isWifiPaused = true, hasFix = true)).text
)
}
@Test
- fun `status text shows location-off message when location services disabled`() {
- // Disabled location takes priority over every other state - the user needs to know.
- assertEquals(
- "Location services off - tracking won't get fixes",
- helper.buildStatusText(false, null, 52.0, 13.0, 0, 0L, locationEnabled = false)
- )
- // Even when paused or stationary, the location-off message wins.
+ fun `a motionless hold names movement as the release`() {
assertEquals(
- "Location services off - tracking won't get fixes",
- helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, locationEnabled = false)
+ "No movement · resumes when you move · All sent",
+ status(input(isPaused = true, isMotionlessPaused = true, hasFix = true)).text
)
}
@Test
- fun `status text shows coordinates when tracking normally`() {
- assertEquals("52.51630, 13.37770", helper.buildStatusText(false, null, 52.51630, 13.37770, 0, 0L))
- }
-
- @Test
- fun `status text shows Synced when queue empty and has synced`() {
- val text = helper.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`() {
- assertEquals("52.00000, 13.00000 (Queued: 15)", helper.buildStatusText(false, null, 52.0, 13.0, 15, 0L))
- }
-
- @Test
- fun `status text shows queued count and last sync when both present`() {
- val now = System.currentTimeMillis()
+ fun `WiFi wins over motionless when both hold`() {
assertEquals(
- "52.00000, 13.00000 (Queued: 7 \u00b7 Just now)",
- helper.buildStatusText(false, null, 52.0, 13.0, 7, now - 30000L)
+ "Zone WiFi · resumes when you leave · All sent",
+ status(input(isPaused = true, isWifiPaused = true, isMotionlessPaused = true, hasFix = true)).text
)
}
@Test
- fun `status text shows Searching GPS when no coordinates`() {
- assertEquals("Searching GPS...", helper.buildStatusText(false, null, null, null, 0, 0L))
+ fun `a pause keeps the queue visible`() {
+ assertEquals(
+ "Inside zone · resumes when you leave · 5 queued · last sync just now",
+ status(input(isPaused = true, hasFix = true, queuedCount = 5, lastSyncTime = NOW - 30_000L)).text
+ )
}
@Test
- fun `status text uses locale-safe coordinate formatting`() {
- val text = helper.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
+ fun `a pause wins over stationary`() {
+ assertEquals("Paused", status(input(isPaused = true, isStationary = true, hasFix = true)).title)
}
@Test
- fun `paused takes priority over coordinates`() {
+ fun `stationary keeps the Tracking title and prefixes Stationary`() {
assertEquals(
- "Paused: Office",
- helper.buildStatusText(true, "Office", 52.0, 13.0, 5, System.currentTimeMillis())
+ NotificationHelper.Status("Tracking", "Stationary · All sent"),
+ status(input(isStationary = true, hasFix = true))
)
}
- // --- shouldThrottle ---
-
@Test
- fun `throttle suppresses within 10s`() {
- setField("lastUpdateTime", 1000L)
- assertTrue(helper.shouldThrottle(now = 5000L))
+ fun `stationary keeps the queue visible`() {
+ assertEquals(
+ "Stationary · 3 queued · last sync 1 h ago",
+ status(input(isStationary = true, hasFix = true, queuedCount = 3, lastSyncTime = NOW - 3_600_000L)).text
+ )
}
- @Test
- fun `throttle allows after 10s`() {
- setField("lastUpdateTime", 1000L)
- assertFalse(helper.shouldThrottle(now = 12000L))
- }
+ // --- formatTimeSinceSync ---
@Test
- fun `throttle allows at exactly 10s`() {
- setField("lastUpdateTime", 1000L)
- assertFalse(helper.shouldThrottle(now = 11000L))
+ fun `under a minute is just now`() {
+ assertEquals("just now", helper.formatTimeSinceSync(NOW - 30_000L, NOW))
}
- // --- shouldFilterByMovement ---
-
@Test
- fun `movement less than 2m is filtered`() {
- assertTrue(helper.shouldFilterByMovement(1.5f))
+ fun `one minute is singular`() {
+ assertEquals("1 min ago", helper.formatTimeSinceSync(NOW - 60_000L, NOW))
}
@Test
- fun `movement of exactly 2m is not filtered`() {
- assertFalse(helper.shouldFilterByMovement(2.0f))
+ fun `minutes under an hour count minutes`() {
+ assertEquals("25 min ago", helper.formatTimeSinceSync(NOW - 1_500_000L, NOW))
}
@Test
- fun `movement greater than 2m is not filtered`() {
- assertFalse(helper.shouldFilterByMovement(5.0f))
+ fun `sixty minutes is 1 h ago`() {
+ assertEquals("1 h ago", helper.formatTimeSinceSync(NOW - 3_600_000L, NOW))
}
- // --- buildTitle ---
-
@Test
- fun `title shows Colota Tracking when no profile active`() {
- assertEquals("Colota Tracking", helper.buildTitle(null))
+ fun `hours under a day count hours`() {
+ assertEquals("5 h ago", helper.formatTimeSinceSync(NOW - 18_000_000L, NOW))
}
@Test
- fun `title includes profile name when active`() {
- assertEquals("Colota \u00b7 Charging", helper.buildTitle("Charging"))
+ fun `twenty-four hours is 1 d ago`() {
+ assertEquals("1 d ago", helper.formatTimeSinceSync(NOW - 86_400_000L, NOW))
}
@Test
- fun `title includes custom profile name`() {
- assertEquals("Colota \u00b7 Fast Driving", helper.buildTitle("Fast Driving"))
+ fun `days count days`() {
+ assertEquals("3 d ago", helper.formatTimeSinceSync(NOW - 3 * 86_400_000L, NOW))
}
// --- Deduplication (via update()) ---
@Test
- fun `same state is deduplicated on second non-forced update`() {
- assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))
- assertFalse(helper.update(lat = 52.52, lon = 13.405, forceUpdate = false))
- }
-
- @Test
- fun `forceUpdate bypasses dedup`() {
- assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))
- assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))
+ fun `an unchanged state within the same minute is not re-posted`() {
+ val s = input(hasFix = true)
+ assertTrue(helper.update(s))
+ assertFalse(helper.update(s.copy(lastFixMs = FIX + 30_000L)))
}
@Test
- fun `different coordinates trigger update`() {
- helper.update(lat = 52.52, lon = 13.405, forceUpdate = true)
- assertTrue(helper.update(lat = 52.521, lon = 13.406, forceUpdate = true))
+ fun `a fix in the next minute re-posts`() {
+ val s = input(hasFix = true)
+ helper.update(s)
+ assertTrue(helper.update(s.copy(lastFixMs = FIX + 60_000L)))
}
@Test
- fun `first update always proceeds`() {
- assertTrue(helper.update(lat = 52.52, lon = 13.405, forceUpdate = true))
+ fun `a queue count change re-posts at once`() {
+ val s = input(hasFix = true)
+ helper.update(s)
+ assertTrue(helper.update(s.copy(queuedCount = 5)))
}
@Test
- fun `queue count change triggers update`() {
- val now = System.currentTimeMillis()
- helper.update(lat = 52.0, lon = 13.0, queuedCount = 0, lastSyncTime = now, forceUpdate = true)
- assertTrue(helper.update(lat = 52.0, lon = 13.0, queuedCount = 5, lastSyncTime = now, forceUpdate = true))
+ fun `forceUpdate re-posts an identical state`() {
+ val s = input(hasFix = true)
+ helper.update(s)
+ assertTrue(helper.update(s, forceUpdate = true))
}
@Test
- fun `profile name change triggers update`() {
- helper.update(lat = 52.0, lon = 13.0, forceUpdate = true)
- assertTrue(helper.update(lat = 52.0, lon = 13.0, activeProfileName = "Charging", forceUpdate = true))
- }
-
- // --- Stationary status ---
-
- @Test
- fun `buildStatusText shows stationary with coords`() {
- val text = helper.buildStatusText(
- isPaused = false, zoneName = null,
- lat = 52.52, lon = 13.405,
- queuedCount = 0, lastSyncTime = 0L,
- isStationary = true
- )
- assertEquals("Stationary - 52.52000, 13.40500", text)
- }
-
- @Test
- fun `buildStatusText shows stationary without coords`() {
- val text = helper.buildStatusText(
- isPaused = false, zoneName = null,
- lat = null, lon = null,
- queuedCount = 0, lastSyncTime = 0L,
- isStationary = true
- )
- assertEquals("Stationary - GPS paused", text)
- }
-
- @Test
- fun `buildStatusText pause zone takes priority over stationary`() {
- val text = helper.buildStatusText(
- isPaused = true, zoneName = "Home",
- lat = 52.52, lon = 13.405,
- queuedCount = 0, lastSyncTime = 0L,
- isStationary = true
- )
- assertEquals("Paused: Home", text)
- }
-
- @Test
- fun `buildStatusText WiFi suffix shown with stationary also active`() {
- val text = helper.buildStatusText(
- isPaused = true, zoneName = "Home",
- lat = 52.52, lon = 13.405,
- queuedCount = 0, lastSyncTime = 0L,
- isStationary = true, isWifiPaused = true
- )
- assertEquals("Paused: Home \u00b7 WiFi", text)
- }
-
- // --- Reflection helper ---
+ fun `the foreground notification primes the dedup key`() {
+ val s = input(hasFix = true)
+ helper.buildForegroundNotification(s)
- private fun setField(name: String, value: Any?) {
- val field = NotificationHelper::class.java.getDeclaredField(name)
- field.isAccessible = true
- field.set(helper, value)
+ assertFalse(helper.update(s))
+ assertTrue(helper.update(s.copy(queuedCount = 3)))
}
}
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 8566ea5a..30d388cb 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
@@ -5,6 +5,7 @@
package com.Colota.triggers
+import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -57,7 +58,7 @@ class LocationBootReceiverTest {
mockkConstructor(DeviceInfoHelper::class)
mockkConstructor(NotificationHelper::class)
every { anyConstructed<NotificationHelper>().createChannel() } just Runs
- every { anyConstructed<NotificationHelper>().buildStoppedNotification(any()) } returns mockk(relaxed = true)
+ every { anyConstructed<NotificationHelper>().buildStoppedNotification(any(), any()) } returns mockk(relaxed = true)
}
@After
@@ -249,10 +250,13 @@ class LocationBootReceiverTest {
mockDbReadyAndDisabled()
every { mockDbHelper.getSetting("stopped_by_battery", "false") } returns "true"
every { anyConstructed<DeviceInfoHelper>().isPluggedIn() } returns false
+ // Without a NotificationManager mock the cast throws and the catch skips the branch under test.
+ every { mockContext.getSystemService(Context.NOTIFICATION_SERVICE) } returns mockk<NotificationManager>(relaxed = true)
callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)
verify { BatteryRecoveryScheduler.schedule(any()) }
+ verify { anyConstructed<NotificationHelper>().buildStoppedNotification(NotificationHelper.STOP_REASON_BATTERY, true) }
verify(exactly = 0) { mockContext.startForegroundService(any()) }
}
diff --git a/fastlane/metadata/android/en-US/changelogs/49.txt b/fastlane/metadata/android/en-US/changelogs/49.txt
index b3062fe4..842c1f81 100644
--- a/fastlane/metadata/android/en-US/changelogs/49.txt
+++ b/fastlane/metadata/android/en-US/changelogs/49.txt
@@ -2,3 +2,5 @@
- Auto-export now deletes old files on storage providers that rename them
- Unplugging at a low battery no longer restarts tracking in a loop
- Pause zones no longer take hours to engage when a tracking profile is active
+- The tracking notification shows the state and the sync queue, never your location, zone or profile name
+- A low-battery stop says tracking resumes when charging