Colota - Android GPS Location tracker
refactor(i18n): move notification and toast strings into Android resources (#917)
Max Dietrichb7f201b4eb8b
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 0fec5e38..37ed7365 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -173,6 +173,8 @@ Handles all notification logic for the tracking service:- 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` and the stopped notification use the same icon and color, so the status bar shows one Colota icon whether tracking runs or has stopped; backup and auto-export keep `ic_menu_save`.- Deduplication to avoid unnecessary notification redraws- Stopped notification, posted on a deliberate stop, by the tracking watchdog when Android refuses a background restart, and by the service itself when Android refuses the location foreground type because location services are off; in both refusal cases 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+- Notification text and channel names live in `res/values/strings.xml`, counts as `<plurals>`. A translation is a `values-<lang>/strings.xml`; a missing key falls back to English+- Stop reasons are the `StopReason` enum. The log and the `onTrackingStopped` event carry its name, the notification its translated text### DatabaseHelperdiff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex 4fb31240..21c73234 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -180,6 +180,7 @@ android {testOptions {unitTests.returnDefaultValues = true+ unitTests.includeAndroidResources = trueunitTests.all {// Bump heap to avoid OOM when running the full test suite.maxHeapSize = "4g"diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.ktindex d066eb90..dfcc2a70 100644--- a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.kt@@ -15,6 +15,7 @@ import android.os.Buildimport android.os.IBinderimport androidx.core.app.NotificationCompatimport androidx.core.content.ContextCompat+import com.Colota.Rimport com.Colota.util.AppLogger// Notification-only shell; work stays in BackupServiceModule's coroutine to keep the password CharArray on heap.@@ -62,10 +63,10 @@ class BackupForegroundService : Service() {}ensureChannel()- val message = intent.getStringExtra(EXTRA_MESSAGE) ?: "Working..."+ val message = intent.getStringExtra(EXTRA_MESSAGE) ?: getString(R.string.backup_working)val notification = NotificationCompat.Builder(this, CHANNEL_ID).setSmallIcon(android.R.drawable.ic_menu_save)- .setContentTitle("Colota Backup")+ .setContentTitle(getString(R.string.backup_title)).setContentText(message).setOngoing(true).setPriority(NotificationCompat.PRIORITY_LOW)@@ -97,12 +98,11 @@ class BackupForegroundService : Service() {private fun ensureChannel() {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) returnval nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager- if (nm.getNotificationChannel(CHANNEL_ID) != null) returnval channel = NotificationChannel(CHANNEL_ID,- "Backup & Restore",+ getString(R.string.channel_backup),NotificationManager.IMPORTANCE_LOW,- ).apply { description = "Shown while a backup or restore is in progress" }+ ).apply { description = getString(R.string.channel_backup_description) }nm.createNotificationChannel(channel)}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.ktindex e3e49231..9c5a5949 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt@@ -9,6 +9,7 @@ import android.content.Intentimport android.net.Uriimport android.os.StatFsimport android.provider.DocumentsContract+import com.Colota.Rimport com.Colota.backup.BackupBuilderimport com.Colota.backup.BackupErrorimport com.Colota.backup.BackupException@@ -158,7 +159,7 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :try {ensureFreeSpaceForBackup()- startForegroundOnMain("Encrypting backup...")+ startForegroundOnMain(reactApplicationContext.getString(R.string.backup_encrypting))pendingFile.outputStream().use { out ->BackupBuilder(reactApplicationContext).build(out, passwordChars)@@ -252,7 +253,7 @@ class BackupServiceModule(reactContext: ReactApplicationContext) :val uri = Uri.parse(uriString)ensureFreeSpaceForRestore(uri)- startForegroundOnMain("Restoring backup...")+ startForegroundOnMain(reactApplicationContext.getString(R.string.backup_restoring))// Read before pauseAllDbWriters clears it, and outside it so a straggler timeout still resumes.trackingWasEnabled = DatabaseHelper.getInstance(reactApplicationContext)diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.ktindex 4c5f0f73..968e0ea0 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt@@ -20,6 +20,7 @@ import androidx.documentfile.provider.DocumentFileimport androidx.work.CoroutineWorkerimport androidx.work.ForegroundInfoimport androidx.work.WorkerParameters+import com.Colota.Rimport com.Colota.bridge.LocationServiceModuleimport com.Colota.data.DatabaseHelperimport com.Colota.util.AppLogger@@ -60,8 +61,8 @@ class AutoExportWorker(ensureNotificationChannel()val notification = NotificationCompat.Builder(appContext, CHANNEL_ID).setSmallIcon(android.R.drawable.ic_menu_save)- .setContentTitle("Auto-Export")- .setContentText("Exporting location data...")+ .setContentTitle(appContext.getString(R.string.auto_export_title))+ .setContentText(appContext.getString(R.string.auto_export_running)).setOngoing(true).build()return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {@@ -91,7 +92,7 @@ class AutoExportWorker(private suspend fun executeWork(isManualRun: Boolean): Result {if (runAttemptCount >= MAX_RETRIES) {AppLogger.e(TAG, "Auto-export failed after $MAX_RETRIES attempts, giving up")- showNotification("Auto-Export Failed", "Export failed after multiple attempts. Please check your settings.")+ showNotification(appContext.getString(R.string.auto_export_failed), appContext.getString(R.string.auto_export_gave_up))return Result.failure()}@@ -162,7 +163,7 @@ class AutoExportWorker(if (rowCount == 0) {tempFile.delete()AppLogger.i(TAG, "No locations to export")- showNotification("Auto-Export", "No new locations to export.")+ showNotification(appContext.getString(R.string.auto_export_title), appContext.getString(R.string.auto_export_nothing_new))cleanupOldExports(dirUri, config)if (isManualRun) LocationServiceModule.sendAutoExportEvent(true, null, 0, null)return Result.success()@@ -186,8 +187,8 @@ class AutoExportWorker(AppLogger.i(TAG, "Auto-export complete: $savedName ($rowCount locations)")config.saveLastResult(db, savedName, rowCount)showNotification(- "Auto-Export Complete",- "Exported $rowCount locations to $savedName",+ appContext.getString(R.string.auto_export_complete),+ appContext.resources.getQuantityString(R.plurals.auto_export_done, rowCount, rowCount, savedName),dirUri)LocationServiceModule.sendAutoExportEvent(true, savedName, rowCount, null)@@ -199,7 +200,7 @@ class AutoExportWorker(tempFile, config, db, e,error = "Directory permission lost",logMessage = "Auto-export failed - permission denied",- userMessage = "Directory permission lost. Please re-select the export directory.",+ userMessage = appContext.getString(R.string.auto_export_permission_lost),retry = false)} catch (e: IllegalArgumentException) {@@ -207,7 +208,7 @@ class AutoExportWorker(tempFile, config, db, e,error = "Invalid configuration: ${e.message}",logMessage = "Auto-export failed - invalid configuration",- userMessage = "Invalid export configuration: ${e.message}",+ userMessage = appContext.getString(R.string.auto_export_invalid_config, e.message.orEmpty()),retry = false)} catch (e: DirectoryAccessException) {@@ -215,7 +216,7 @@ class AutoExportWorker(tempFile, config, db, e,error = "Directory access failed: ${e.message}",logMessage = "Auto-export failed - directory access issue",- userMessage = "Could not access export directory: ${e.message}",+ userMessage = appContext.getString(R.string.auto_export_directory_failed, e.message.orEmpty()),retry = false)} catch (e: SQLException) {@@ -223,7 +224,7 @@ class AutoExportWorker(tempFile, config, db, e,error = "Read failed: ${e.message}",logMessage = "Auto-export failed - database read, will retry",- userMessage = "Could not read locations. Will retry.",+ userMessage = appContext.getString(R.string.auto_export_read_failed),retry = true)} catch (e: IOException) {@@ -231,7 +232,7 @@ class AutoExportWorker(tempFile, config, db, e,error = "IO error: ${e.message}",logMessage = "Auto-export failed - IO error, will retry",- userMessage = "Could not save export file. Will retry.",+ userMessage = appContext.getString(R.string.auto_export_save_failed),retry = true)} catch (e: Exception) {@@ -239,7 +240,7 @@ class AutoExportWorker(tempFile, config, db, e,error = "Export failed: ${e.message}",logMessage = "Auto-export failed",- userMessage = "Could not save export file. Will retry.",+ userMessage = appContext.getString(R.string.auto_export_save_failed),retry = true)}@@ -258,7 +259,7 @@ class AutoExportWorker(tempFile.delete()AppLogger.e(TAG, logMessage, e)config.saveLastError(db, error)- showNotification("Auto-Export Failed", userMessage)+ showNotification(appContext.getString(R.string.auto_export_failed), userMessage)LocationServiceModule.sendAutoExportEvent(false, null, 0, error)return if (retry) Result.retry() else Result.failure()}@@ -352,10 +353,10 @@ class AutoExportWorker(val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagerval channel = NotificationChannel(CHANNEL_ID,- "Auto-Export",+ appContext.getString(R.string.channel_auto_export),NotificationManager.IMPORTANCE_LOW).apply {- description = "Notifications for automatic data exports"+ description = appContext.getString(R.string.channel_auto_export_description)}nm.createNotificationChannel(channel)}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.ktindex 0a1c37f2..05a285cf 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@@ -43,8 +43,8 @@ class BatteryRecoveryWorker(val notification = NotificationCompat.Builder(appContext, CHANNEL_ID).setSmallIcon(R.drawable.ic_notification).setColor(NotificationHelper.ICON_COLOR)- .setContentTitle("Resuming tracking")- .setContentText("Charger connected - restarting location tracking")+ .setContentTitle(appContext.getString(R.string.battery_recovery_title))+ .setContentText(appContext.getString(R.string.battery_recovery_text)).setOngoing(true).build()return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {@@ -116,10 +116,10 @@ class BatteryRecoveryWorker(val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagerval channel = NotificationChannel(CHANNEL_ID,- "Battery Recovery",+ appContext.getString(R.string.channel_battery_recovery),NotificationManager.IMPORTANCE_LOW).apply {- description = "Resuming tracking after a low-battery stop"+ description = appContext.getString(R.string.channel_battery_recovery_description)}nm.createNotificationChannel(channel)}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.ktindex 8d29b076..de235b37 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@@ -356,7 +356,7 @@ class LocationForegroundService : Service() {TrackingWatchdogScheduler.scheduleLocationOffRetry(this)notificationManager.notify(NotificationHelper.STOPPED_NOTIFICATION_ID,- notificationHelper.buildStoppedNotification(NotificationHelper.STOP_REASON_LOCATION_OFF, unexpected = true)+ notificationHelper.buildStoppedNotification(NotificationHelper.StopReason.LOCATION_OFF, unexpected = true))} else {TrackingWatchdogScheduler.schedule(this)@@ -393,7 +393,9 @@ class LocationForegroundService : Service() {ACTION_STATIONARY_HEARTBEAT -> handleStationaryHeartbeatFired()ACTION_GEOFENCE_HEARTBEAT -> handleGeofenceHeartbeatFired(shouldBeTracking)ACTION_STOP_REQUEST -> stopForegroundServiceWithReason(- intent?.getStringExtra(EXTRA_STOP_REASON) ?: "Stopped",+ intent?.getStringExtra(EXTRA_STOP_REASON)+ ?.let { name -> NotificationHelper.StopReason.entries.firstOrNull { it.name == name } }+ ?: NotificationHelper.StopReason.OTHER,unexpected = false)else -> handleStart()@@ -524,7 +526,7 @@ class LocationForegroundService : Service() {if (deviceInfoHelper.isBatteryCritical()) {val (level, _) = deviceInfoHelper.getCachedBatteryStatus()AppLogger.d(TAG, "Battery critical ($level%) and unplugged - stopping service")- stopForegroundServiceWithReason(NotificationHelper.STOP_REASON_BATTERY, stoppedByBattery = true)+ stopForegroundServiceWithReason(NotificationHelper.StopReason.BATTERY, stoppedByBattery = true)return}@@ -573,10 +575,10 @@ class LocationForegroundService : Service() {startPauseWatchdog()} catch (e: SecurityException) {AppLogger.e(TAG, "Location permission missing", e)- stopForegroundServiceWithReason("Location permission missing")+ stopForegroundServiceWithReason(NotificationHelper.StopReason.PERMISSION)} catch (e: Exception) {AppLogger.e(TAG, "Failed to start location updates", e)- stopForegroundServiceWithReason("Location provider error")+ stopForegroundServiceWithReason(NotificationHelper.StopReason.PROVIDER)}}@@ -1448,24 +1450,24 @@ class LocationForegroundService : Service() {/** Fired by [batteryMonitor] on a critical-battery broadcast. */private fun onBatteryCritical() {AppLogger.i(TAG, "Battery critical and unplugged - stopping (battery monitor)")- stopForegroundServiceWithReason(NotificationHelper.STOP_REASON_BATTERY, stoppedByBattery = true)+ stopForegroundServiceWithReason(NotificationHelper.StopReason.BATTERY, stoppedByBattery = true)}private fun stopForegroundServiceWithReason(- reason: String,+ reason: NotificationHelper.StopReason,stoppedByBattery: Boolean = false,unexpected: Boolean = true) {if (isStopping) returnisStopping = true- AppLogger.i(TAG, "Stopping: $reason")+ AppLogger.i(TAG, "Stopping: ${reason.name}")// Reset profile indicator in JS UIif (profileManager.getActiveProfileName() != null) {LocationServiceModule.sendProfileSwitchEvent(null, null)}- LocationServiceModule.sendTrackingStoppedEvent(reason)+ LocationServiceModule.sendTrackingStoppedEvent(reason.name)dbHelper.saveSetting(SettingsKeys.TRACKING_ENABLED, "false")dbHelper.saveSetting(SettingsKeys.STOPPED_BY_BATTERY, if (stoppedByBattery) "true" else "false")if (stoppedByBattery) BatteryRecoveryScheduler.schedule(this)diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.ktindex acebc3b1..e51d0465 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@@ -9,6 +9,7 @@ import android.app.*import android.content.Contextimport android.content.Intentimport android.os.Build+import androidx.annotation.StringResimport androidx.core.app.NotificationCompatimport com.Colota.MainActivityimport com.Colota.R@@ -39,6 +40,18 @@ class NotificationHelper(data class Status(val title: String, val text: String)+ /** Logged and sent over the bridge by name; only the notification shows the text. */+ enum class StopReason(@StringRes val text: Int) {+ BATTERY(R.string.stop_reason_battery),+ LOCATION_OFF(R.string.stop_reason_location_off),+ PERMISSION(R.string.stop_reason_permission),+ PROVIDER(R.string.stop_reason_provider),+ KILLED(R.string.stop_reason_killed),+ SHORTCUT(R.string.stop_reason_shortcut),+ AUTOMATION(R.string.stop_reason_automation),+ OTHER(R.string.stop_reason_other)+ }+private var lastKey: String? = null/** From Android 12 the collapsed row shows the app name only when there is no title. */@@ -49,30 +62,27 @@ class NotificationHelper(const val STOPPED_CHANNEL_ID = "tracking_stopped_channel"const val NOTIFICATION_ID = 1const val STOPPED_NOTIFICATION_ID = 2- const val STOP_REASON_BATTERY = "Battery fell below 5% · resumes when charging"- const val STOP_REASON_LOCATION_OFF =- "Location services are off · tap to resume now, or it resumes by itself within 10 min of turning them on"- /** ic_launcher_background, copied because unit tests run without app resources. */+ /** ic_launcher_background. */const val ICON_COLOR = 0xFF0D9387.toInt()}fun createChannel() {val channel = NotificationChannel(CHANNEL_ID,- "Location Tracking",+ context.getString(R.string.channel_tracking),NotificationManager.IMPORTANCE_LOW).apply {- description = "Shows active tracking status and sync queue"+ description = context.getString(R.string.channel_tracking_description)setShowBadge(false)}notificationManager.createNotificationChannel(channel)val stoppedChannel = NotificationChannel(STOPPED_CHANNEL_ID,- "Tracking stopped",+ context.getString(R.string.channel_stopped),NotificationManager.IMPORTANCE_DEFAULT).apply {- description = "Alerts when tracking stops without you asking it to"+ description = context.getString(R.string.channel_stopped_description)setShowBadge(true)}notificationManager.createNotificationChannel(stoppedChannel)@@ -106,7 +116,7 @@ class NotificationHelper(* @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.*/- fun buildStoppedNotification(reason: String, unexpected: Boolean = false): Notification {+ fun buildStoppedNotification(reason: StopReason, unexpected: Boolean = false): Notification {// Opening the app is the recovery path when the watchdog cannot restart the service// itself, so this notification has to be tappable.val pendingIntent = PendingIntent.getActivity(@@ -116,13 +126,15 @@ class NotificationHelper(PendingIntent.FLAG_IMMUTABLE)+ val title = context.getString(R.string.stopped_title)+ val text = context.getString(reason.text)return NotificationCompat.Builder(context,if (unexpected) STOPPED_CHANNEL_ID else CHANNEL_ID)- .setContentTitle(collapsedTitle("Tracking stopped"))- .setContentText(collapsedText("Tracking stopped", reason))- .setStyle(NotificationCompat.BigTextStyle().setBigContentTitle("Tracking stopped").bigText(reason))+ .setContentTitle(collapsedTitle(title))+ .setContentText(collapsedText(title, text))+ .setStyle(NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(text)).setSmallIcon(R.drawable.ic_notification).setColor(ICON_COLOR).setOngoing(false)@@ -142,39 +154,43 @@ class NotificationHelper(/** Title is the recording state, text the sending state. */fun buildStatus(input: StatusInput, now: Long = System.currentTimeMillis()): Status {val send = sendSegment(input, now)+ val tracking = str(R.string.status_tracking)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)+ !input.locationEnabled -> Status(str(R.string.status_location_off), "${str(R.string.status_not_recording)} · $send")+ input.isPaused -> Status(str(R.string.status_paused), "${pauseDetail(input)} · $send")+ !input.hasFix -> Status(str(R.string.status_searching), send)+ input.isStationary -> Status(tracking, "${str(R.string.status_stationary)} · $send")+ else -> Status(tracking, send)}}+ private fun str(@StringRes id: Int, vararg args: Any): String =+ if (args.isEmpty()) context.getString(id) else context.getString(id, *args)++ private fun count(id: Int, n: Int): String = context.resources.getQuantityString(id, n, n)+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"+ input.isWifiPaused -> str(R.string.status_pause_wifi)+ input.isMotionlessPaused -> str(R.string.status_pause_motionless)+ else -> str(R.string.status_pause_zone)}private fun sendSegment(input: StatusInput, now: Long): String = when {- input.isOfflineMode -> "Offline mode"+ input.isOfflineMode -> str(R.string.status_offline)input.queuedCount > 0 && input.lastSyncTime > 0 ->- "${input.queuedCount} queued · last sync ${formatTimeSinceSync(input.lastSyncTime, now)}"- input.queuedCount > 0 -> "${input.queuedCount} queued"- else -> "All sent"+ "${count(R.plurals.status_queued, input.queuedCount)} · " ++ str(R.string.status_last_sync, formatTimeSinceSync(input.lastSyncTime, now))+ input.queuedCount > 0 -> count(R.plurals.status_queued, input.queuedCount)+ else -> str(R.string.status_all_sent)}fun formatTimeSinceSync(lastSyncTime: Long, now: Long): String {val minutes = ((now - lastSyncTime) / 60_000).toInt()return when {- 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"+ minutes < 1 -> str(R.string.sync_just_now)+ minutes < 60 -> count(R.plurals.sync_minutes_ago, minutes)+ minutes < 1440 -> count(R.plurals.sync_hours_ago, minutes / 60)+ else -> count(R.plurals.sync_days_ago, minutes / 1440)}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.ktindex d18f85fa..18395a73 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/TrackingWatchdogReceiver.kt@@ -86,7 +86,7 @@ class TrackingWatchdogReceiver : BroadcastReceiver() {it.createChannel()notificationManager.notify(NotificationHelper.STOPPED_NOTIFICATION_ID,- it.buildStoppedNotification("Tracking service was killed - tap to resume", unexpected = true)+ it.buildStoppedNotification(NotificationHelper.StopReason.KILLED, unexpected = 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.ktindex 81ab27f1..fc9f0a1b 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(- NotificationHelper.STOP_REASON_BATTERY,+ NotificationHelper.StopReason.BATTERY,unexpected = true))diff --git a/apps/mobile/android/app/src/main/java/com/colota/triggers/ShortcutHandlerActivity.kt b/apps/mobile/android/app/src/main/java/com/colota/triggers/ShortcutHandlerActivity.ktindex d6b8ca27..c017d31c 100644--- a/apps/mobile/android/app/src/main/java/com/colota/triggers/ShortcutHandlerActivity.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/triggers/ShortcutHandlerActivity.kt@@ -8,6 +8,7 @@ package com.Colota.triggersimport android.app.Activityimport android.content.Contextimport android.os.Bundle+import com.Colota.service.NotificationHelperimport com.Colota.util.AppLoggerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -52,6 +53,6 @@ class ShortcutHandlerActivity : Activity() {private fun handleStop(context: Context) {AppLogger.d(TAG, "Shortcut: stop tracking")- TrackingControl.stop(context, "Stopped via shortcut")+ TrackingControl.stop(context, NotificationHelper.StopReason.SHORTCUT)}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt b/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.ktindex 178438cf..65c1e7b5 100644--- a/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControl.kt@@ -9,6 +9,7 @@ import android.content.Contextimport android.content.Intentimport com.Colota.data.DatabaseHelperimport com.Colota.service.LocationForegroundService+import com.Colota.service.NotificationHelper/*** Shared start/stop tracking actions for external triggers (app shortcut,@@ -22,10 +23,10 @@ object TrackingControl {// Route stop through the service so stopForegroundServiceWithReason runs - direct// stopService skips the pause-zone flag clearing and the stopped notification.- fun stop(context: Context, stopReason: String) {+ fun stop(context: Context, stopReason: NotificationHelper.StopReason) {val stopIntent = Intent(context, LocationForegroundService::class.java).apply {action = LocationForegroundService.ACTION_STOP_REQUEST- putExtra(LocationForegroundService.EXTRA_STOP_REASON, stopReason)+ putExtra(LocationForegroundService.EXTRA_STOP_REASON, stopReason.name)}context.startService(stopIntent)}diff --git a/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControlReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControlReceiver.ktindex 7125c74f..48f5d898 100644--- a/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControlReceiver.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/triggers/TrackingControlReceiver.kt@@ -11,6 +11,8 @@ import android.content.Intentimport android.os.Handlerimport android.os.Looperimport android.widget.Toast+import com.Colota.R+import com.Colota.service.NotificationHelperimport com.Colota.util.AppLoggerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -51,13 +53,13 @@ class TrackingControlReceiver : BroadcastReceiver() {private fun handleStart(context: Context) {AppLogger.d(TAG, "Broadcast: start tracking")TrackingControl.start(context, "Started via automation intent")- toastOnMain(context, "Colota tracking started")+ toastOnMain(context, context.getString(R.string.toast_tracking_started))}private fun handleStop(context: Context) {AppLogger.d(TAG, "Broadcast: stop tracking")- TrackingControl.stop(context, "Stopped via automation intent")- toastOnMain(context, "Colota tracking stopped")+ TrackingControl.stop(context, NotificationHelper.StopReason.AUTOMATION)+ toastOnMain(context, context.getString(R.string.toast_tracking_stopped))}private fun toastOnMain(context: Context, message: String) {diff --git a/apps/mobile/android/app/src/main/res/values/strings.xml b/apps/mobile/android/app/src/main/res/values/strings.xmlindex 59258b10..fc65cd2e 100644--- a/apps/mobile/android/app/src/main/res/values/strings.xml+++ b/apps/mobile/android/app/src/main/res/values/strings.xml@@ -4,4 +4,82 @@<string name="shortcut_start_long">Start Tracking</string><string name="shortcut_stop_short">Stop</string><string name="shortcut_stop_long">Stop Tracking</string>++ <string name="channel_tracking">Location Tracking</string>+ <string name="channel_tracking_description">Shows active tracking status and sync queue</string>+ <string name="channel_stopped">Tracking stopped</string>+ <string name="channel_stopped_description">Alerts when tracking stops without you asking it to</string>+ <string name="channel_auto_export">Auto-Export</string>+ <string name="channel_auto_export_description">Notifications for automatic data exports</string>+ <string name="channel_backup">Backup & Restore</string>+ <string name="channel_backup_description">Shown while a backup or restore is in progress</string>+ <string name="channel_battery_recovery">Battery Recovery</string>+ <string name="channel_battery_recovery_description">Resuming tracking after a low-battery stop</string>++ <string name="status_location_off">Location services are off</string>+ <string name="status_paused">Paused</string>+ <string name="status_searching">Searching for GPS</string>+ <string name="status_tracking">Tracking</string>+ <string name="status_not_recording">Not recording</string>+ <string name="status_stationary">Stationary</string>+ <string name="status_pause_wifi">Zone WiFi · resumes when you leave</string>+ <string name="status_pause_motionless">No movement · resumes when you move</string>+ <string name="status_pause_zone">Inside zone · resumes when you leave</string>+ <string name="status_offline">Offline mode</string>+ <string name="status_all_sent">All sent</string>+ <plurals name="status_queued">+ <item quantity="one">%d queued</item>+ <item quantity="other">%d queued</item>+ </plurals>+ <string name="status_last_sync">last sync %s</string>+ <string name="sync_just_now">just now</string>+ <plurals name="sync_minutes_ago">+ <item quantity="one">%d min ago</item>+ <item quantity="other">%d min ago</item>+ </plurals>+ <plurals name="sync_hours_ago">+ <item quantity="one">%d h ago</item>+ <item quantity="other">%d h ago</item>+ </plurals>+ <plurals name="sync_days_ago">+ <item quantity="one">%d d ago</item>+ <item quantity="other">%d d ago</item>+ </plurals>++ <string name="stopped_title">Tracking stopped</string>+ <string name="stop_reason_battery" formatted="false">Battery fell below 5% · resumes when charging</string>+ <string name="stop_reason_location_off">Location services are off · tap to resume now, or it resumes by itself within 10 min of turning them on</string>+ <string name="stop_reason_permission">Location permission missing</string>+ <string name="stop_reason_provider">Location provider error</string>+ <string name="stop_reason_killed">Tracking service was killed - tap to resume</string>+ <string name="stop_reason_shortcut">Stopped via shortcut</string>+ <string name="stop_reason_automation">Stopped via automation intent</string>+ <string name="stop_reason_other">Stopped</string>++ <string name="toast_tracking_started">Colota tracking started</string>+ <string name="toast_tracking_stopped">Colota tracking stopped</string>++ <string name="auto_export_title">Auto-Export</string>+ <string name="auto_export_running">Exporting location data...</string>+ <string name="auto_export_nothing_new">No new locations to export.</string>+ <string name="auto_export_complete">Auto-Export Complete</string>+ <plurals name="auto_export_done">+ <item quantity="one">Exported %1$d location to %2$s</item>+ <item quantity="other">Exported %1$d locations to %2$s</item>+ </plurals>+ <string name="auto_export_failed">Auto-Export Failed</string>+ <string name="auto_export_permission_lost">Directory permission lost. Please re-select the export directory.</string>+ <string name="auto_export_invalid_config">Invalid export configuration: %s</string>+ <string name="auto_export_directory_failed">Could not access export directory: %s</string>+ <string name="auto_export_read_failed">Could not read locations. Will retry.</string>+ <string name="auto_export_save_failed">Could not save export file. Will retry.</string>+ <string name="auto_export_gave_up">Export failed after multiple attempts. Please check your settings.</string>++ <string name="backup_title">Colota Backup</string>+ <string name="backup_working">Working...</string>+ <string name="backup_encrypting">Encrypting backup...</string>+ <string name="backup_restoring">Restoring backup...</string>++ <string name="battery_recovery_title">Resuming tracking</string>+ <string name="battery_recovery_text">Charger connected - restarting location tracking</string></resources>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 c1b28fb2..a9a568fc 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@@ -2207,11 +2207,33 @@ class LocationForegroundServiceTest {verify { notificationHelper.buildStoppedNotification(any(), false) }}+ @Test+ fun `a stop request names the source it came from`() = runServiceTest {+ val intent = intentFor(LocationForegroundService.ACTION_STOP_REQUEST)+ every { intent.getStringExtra(LocationForegroundService.EXTRA_STOP_REASON) } returns "SHORTCUT"++ service.onStartCommand(intent, 0, 1)+ advanceUntilIdle()++ verify { notificationHelper.buildStoppedNotification(NotificationHelper.StopReason.SHORTCUT, false) }+ }++ @Test+ fun `a stop request with an unknown reason still stops, as a plain stop`() = runServiceTest {+ val intent = intentFor(LocationForegroundService.ACTION_STOP_REQUEST)+ every { intent.getStringExtra(LocationForegroundService.EXTRA_STOP_REASON) } returns "Stopped via shortcut"++ service.onStartCommand(intent, 0, 1)+ advanceUntilIdle()++ verify { notificationHelper.buildStoppedNotification(NotificationHelper.StopReason.OTHER, false) }+ }+@Testfun `a stop the user did not ask for alerts`() {- invokeStopWithReason("Location permission missing", false)+ invokeStopWithReason(NotificationHelper.StopReason.PERMISSION, false)- verify { notificationHelper.buildStoppedNotification("Location permission missing", true) }+ verify { notificationHelper.buildStoppedNotification(NotificationHelper.StopReason.PERMISSION, true) }}@Test@@ -2227,7 +2249,7 @@ class LocationForegroundServiceTest {fun `stopForBattery sends tracking stopped event`() {invokeOnBatteryCritical()- verify { LocationServiceModule.sendTrackingStoppedEvent("Battery fell below 5% \u00b7 resumes when charging") }+ verify { LocationServiceModule.sendTrackingStoppedEvent("BATTERY") }}@Test@@ -2262,7 +2284,7 @@ class LocationForegroundServiceTest {@Testfun `non-battery stop clears stopped_by_battery and does not arm recovery`() {- invokeStopWithReason("Location permission missing", stoppedByBattery = false)+ invokeStopWithReason(NotificationHelper.StopReason.PERMISSION, stoppedByBattery = false)verify { dbHelper.saveSetting("stopped_by_battery", "false") }verify(exactly = 0) { BatteryRecoveryScheduler.schedule(any()) }@@ -2681,13 +2703,13 @@ class LocationForegroundServiceTest {}private fun invokeStopWithReason(- reason: String,+ reason: NotificationHelper.StopReason,stoppedByBattery: Boolean,unexpected: Boolean = true) {val method = LocationForegroundService::class.java.getDeclaredMethod("stopForegroundServiceWithReason",- String::class.java,+ NotificationHelper.StopReason::class.java,Boolean::class.javaPrimitiveType,Boolean::class.javaPrimitiveType)@@ -3532,7 +3554,7 @@ class LocationForegroundServiceTest {every { deviceInfoHelper.isLocationEnabled() } returns falserefuseStartForeground()val stopped = mockk<android.app.Notification>(relaxed = true)- every { notificationHelper.buildStoppedNotification(NotificationHelper.STOP_REASON_LOCATION_OFF, true) } returns stopped+ every { notificationHelper.buildStoppedNotification(NotificationHelper.StopReason.LOCATION_OFF, true) } returns stoppedval result = service.onStartCommand(intentFor(null), 0, 1)advanceUntilIdle()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.ktindex 3787755c..c32f9cac 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@@ -14,12 +14,13 @@ import org.robolectric.Shadows.shadowOfimport org.robolectric.annotation.Config/**- * Tests for NotificationHelper using a real instance with mocked Android deps:+ * Tests for NotificationHelper using a real instance on the Robolectric app context:* - Status building* - Time-since-last-sync formatting* - Deduplication* - Posted notification fields (Robolectric)*/+@RunWith(RobolectricTestRunner::class)class NotificationHelperTest {companion object {@@ -58,7 +59,7 @@ class NotificationHelperTest {val (helper, _) = helperFor()helper.createChannel()- val n = helper.buildStoppedNotification("killed", unexpected = true)+ val n = helper.buildStoppedNotification(NotificationHelper.StopReason.KILLED, unexpected = true)assertEquals(NotificationHelper.STOPPED_CHANNEL_ID, n.channelId)}@@ -68,7 +69,7 @@ class NotificationHelperTest {val (helper, _) = helperFor()helper.createChannel()- val n = helper.buildStoppedNotification("stopped via shortcut", unexpected = false)+ val n = helper.buildStoppedNotification(NotificationHelper.StopReason.SHORTCUT, unexpected = false)assertEquals(NotificationHelper.CHANNEL_ID, n.channelId)}@@ -137,12 +138,12 @@ class NotificationHelperTest {@Testfun `the stopped notification keeps the full reason in the expanded view`() {- val n = helper.buildStoppedNotification("killed", unexpected = true)+ val n = helper.buildStoppedNotification(NotificationHelper.StopReason.KILLED, unexpected = true)assertNull(n.extras.getString(Notification.EXTRA_TITLE))- assertEquals("Tracking stopped · killed", n.extras.getString(Notification.EXTRA_TEXT))+ assertEquals("Tracking stopped · Tracking service was killed - tap to resume", 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))+ assertEquals("Tracking service was killed - tap to resume", n.extras.getString(Notification.EXTRA_BIG_TEXT))}@Test@@ -159,9 +160,15 @@ class NotificationHelperTest {assertEquals(0xFF0D9387.toInt(), posted().color)}+ @Test+ fun `the icon color constant is the launcher background resource`() {+ val app = RuntimeEnvironment.getApplication()+ assertEquals(app.getColor(R.color.ic_launcher_background), NotificationHelper.ICON_COLOR)+ }+@Testfun `the stopped notification carries the same icon and color`() {- val n = helper.buildStoppedNotification("killed", unexpected = true)+ val n = helper.buildStoppedNotification(NotificationHelper.StopReason.KILLED, unexpected = true)assertEquals(R.drawable.ic_notification, n.smallIcon.resId)assertEquals(0xFF0D9387.toInt(), n.color)@@ -188,8 +195,8 @@ class NotificationHelperTest {@Testfun `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)+ assertEquals(Notification.VISIBILITY_PUBLIC, helper.buildStoppedNotification(NotificationHelper.StopReason.KILLED, unexpected = true).visibility)+ assertEquals(Notification.VISIBILITY_PUBLIC, helper.buildStoppedNotification(NotificationHelper.StopReason.OTHER, unexpected = false).visibility)}@Test@@ -215,7 +222,7 @@ class NotificationHelperTest {@Beforefun setUp() {helper = spyk(- NotificationHelper(mockk(relaxed = true), mockk(relaxed = true))+ NotificationHelper(RuntimeEnvironment.getApplication(), mockk(relaxed = true)))// Stub buildTrackingNotification to avoid PendingIntent.getActivity()every { helper.buildTrackingNotification(any(), any()) } returns mockk()@@ -243,6 +250,19 @@ class NotificationHelperTest {assertEquals("12 queued", status(input(hasFix = true, queuedCount = 12)).text)}+ @Test+ fun `a single queued point reads 1 queued`() {+ assertEquals("1 queued", status(input(hasFix = true, queuedCount = 1)).text)+ }++ // The worker passes the count twice, once to pick the form and once to print it, then the file name.+ @Test+ fun `the export result names the count in the right form and then the file`() {+ val res = RuntimeEnvironment.getApplication().resources+ assertEquals("Exported 1 location to f.geojson", res.getQuantityString(R.plurals.auto_export_done, 1, 1, "f.geojson"))+ assertEquals("Exported 2 locations to f.geojson", res.getQuantityString(R.plurals.auto_export_done, 2, 2, "f.geojson"))+ }+@Testfun `an empty queue reads All sent regardless of the last sync time`() {assertEquals("All sent", status(input(hasFix = true, lastSyncTime = 0L)).text)@@ -363,6 +383,13 @@ class NotificationHelperTest {assertEquals("1 d ago", helper.formatTimeSinceSync(NOW - 86_400_000L, NOW))}+ @Test+ fun `every stop reason has its own text`() {+ val ctx = RuntimeEnvironment.getApplication()+ val texts = NotificationHelper.StopReason.entries.map { ctx.getString(it.text) }+ assertEquals(texts.size, texts.toSet().size)+ }+@Testfun `days count days`() {assertEquals("3 d ago", helper.formatTimeSinceSync(NOW - 3 * 86_400_000L, NOW))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.ktindex 30d388cb..3563bd13 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@@ -256,7 +256,7 @@ class LocationBootReceiverTest {callHandleBootCompleted(mockContext, Intent.ACTION_BOOT_COMPLETED)verify { BatteryRecoveryScheduler.schedule(any()) }- verify { anyConstructed<NotificationHelper>().buildStoppedNotification(NotificationHelper.STOP_REASON_BATTERY, true) }+ verify { anyConstructed<NotificationHelper>().buildStoppedNotification(NotificationHelper.StopReason.BATTERY, true) }verify(exactly = 0) { mockContext.startForegroundService(any()) }}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/triggers/TrackingControlTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/triggers/TrackingControlTest.ktnew file mode 100644index 00000000..99a8e00e--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/triggers/TrackingControlTest.kt@@ -0,0 +1,25 @@+package com.Colota.triggers++import com.Colota.service.LocationForegroundService+import com.Colota.service.NotificationHelper+import org.junit.Assert.assertEquals+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class TrackingControlTest {++ @Test+ fun `a stop goes through the service and carries its reason by name`() {+ val app = RuntimeEnvironment.getApplication()++ TrackingControl.stop(app, NotificationHelper.StopReason.AUTOMATION)++ val started = shadowOf(app).nextStartedService+ assertEquals(LocationForegroundService.ACTION_STOP_REQUEST, started.action)+ assertEquals("AUTOMATION", started.getStringExtra(LocationForegroundService.EXTRA_STOP_REASON))+ }+}diff --git a/apps/mobile/android/app/src/test/resources/robolectric.properties b/apps/mobile/android/app/src/test/resources/robolectric.propertiesindex 979b5eeb..33eb3e64 100644--- a/apps/mobile/android/app/src/test/resources/robolectric.properties+++ b/apps/mobile/android/app/src/test/resources/robolectric.properties@@ -1 +1,3 @@sdk=34+# MainApplication boots React Native's SoLoader, which crashes on the JVM.+application=android.app.Application