Skip to content

Colota - Android GPS Location tracker

Feat/pause gps when stationary (#224)

Max Dietrich59da74f4ec92
diff --git a/apps/docs/docs/configuration/gps-settings.md b/apps/docs/docs/configuration/gps-settings.md
index fb4e7d45..9a1ecff2 100644
--- a/apps/docs/docs/configuration/gps-settings.md
+++ b/apps/docs/docs/configuration/gps-settings.md
@@ -6,12 +6,13 @@ sidebar_position: 2
## Available Settings
-| Setting | Description | Default | Range |
-| ------------------ | ------------------------------------ | --------- | ---------- |
-| Tracking Interval | Time between GPS fixes | 5 seconds | 1s - hours |
-| Movement Threshold | Minimum movement to trigger update | 0 meters | 0m - 1000m |
-| Accuracy Threshold | Filter out fixes above this accuracy | 50 meters | 1m - 1000m |
-| Filter Inaccurate | Enable/disable accuracy filtering | Disabled | On/Off |
+| Setting | Description | Default | Range |
+| ------------------------- | ------------------------------------------ | --------- | ---------- |
+| Tracking Interval | Time between GPS fixes | 5 seconds | 1s - hours |
+| Movement Threshold | Minimum movement to trigger update | 0 meters | 0m - 1000m |
+| Accuracy Threshold | Filter out fixes above this accuracy | 50 meters | 1m - 1000m |
+| Filter Inaccurate | Enable/disable accuracy filtering | Disabled | On/Off |
+| Pause GPS when stationary | Stop active GPS after 60s without movement | Enabled | On/Off |
## Tracking Interval
@@ -33,3 +34,28 @@ Only records a new location if you've moved at least this many meters since the
When enabled, GPS fixes with accuracy worse than the threshold are discarded. This prevents recording poor-quality positions from indoor or urban environments.
The Google Play variant uses Android's `HIGH_ACCURACY` positioning mode via FusedLocationProvider, which combines GPS, Wi-Fi, and cellular data. The FOSS variant uses Android's native `LocationManager` with `GPS_PROVIDER` directly.
+
+## Pause GPS When Stationary
+
+When enabled, Colota automatically pauses active GPS after 60 seconds of no movement (speed below ~1 km/h). This is the single biggest battery saver for most users, since people are stationary for most of the day.
+
+**How it works:**
+
+1. Speed stays below the threshold for 60 seconds
+2. Active GPS is stopped - no more battery-draining satellite fixes
+3. The hardware significant motion sensor is armed (near-zero power consumption)
+4. When the device starts moving again, the motion sensor fires and active GPS resumes immediately
+
+This uses Android's `TYPE_SIGNIFICANT_MOTION` sensor, which runs entirely in the device's sensor hub and consumes virtually no battery while waiting for motion.
+
+**Interaction with Accuracy Filter:**
+
+Stationary detection only evaluates fixes that pass the accuracy filter. However, once the 60-second countdown starts it runs uninterrupted - gaps where all fixes are filtered out do not reset the timer. In practice this means:
+
+- A tight accuracy threshold (e.g. 10m) may delay the start of the countdown in poor signal conditions, since fewer fixes get through to trigger it.
+- Once the countdown has started, it will complete even if subsequent fixes are filtered, as long as no fix with speed above ~1 km/h gets through.
+- Very tight accuracy thresholds indoors (where GPS signal is weak) can significantly delay or prevent stationary detection entirely.
+
+If you use a tight accuracy threshold and care about battery life, consider loosening it slightly or leaving the accuracy filter disabled.
+
+**Note:** Not all devices have a significant motion sensor. If the sensor is unavailable, this setting has no effect and GPS runs continuously as normal.
diff --git a/apps/docs/docs/guides/battery-optimization.md b/apps/docs/docs/guides/battery-optimization.md
index ec9849c0..46e02ac9 100644
--- a/apps/docs/docs/guides/battery-optimization.md
+++ b/apps/docs/docs/guides/battery-optimization.md
@@ -8,6 +8,7 @@ Settings and tips to reduce battery usage without losing GPS fixes.
## Built-in Optimizations
+- **Stationary detection**: Automatically pauses GPS after 60s without movement, resumes on motion via hardware sensor (enabled by default)
- **Notification throttling**: Max 1 update per 10 seconds, plus 2-meter movement filter
- **Batch processing**: 50 items per batch, 10 concurrent network requests
- **Smart sync**: Only syncs when queue has items and network is available
@@ -18,7 +19,7 @@ Settings and tips to reduce battery usage without losing GPS fixes.
1. **Increase GPS interval** - 5s to 30s saves significant battery
2. **Enable accuracy filtering** - Reject poor GPS fixes to avoid unnecessary processing
3. **Use batch sync** instead of instant - Reduces network usage and wake-ups
-4. **Create geofences** for home/work - Stops recording locations in zones
+4. **Create geofences** for home/work - Stops recording locations in zones, and GPS is also paused after 60s stationary inside a zone
5. **Enable movement threshold** - 10-50m, skip stationary updates
6. **Disable battery optimization** for Colota in Android settings to prevent the OS from killing the service
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 2aa60c6e..27ec03c3 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -28,6 +28,8 @@ import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
- Zone detection uses the Haversine formula (1-2ms per check)
- When entering a pause zone, location recording and syncing stops
- The notification shows "Paused: [Zone Name]"
+- GPS continues running inside the zone to detect when you leave
+- If you stay stationary inside a zone, GPS is paused after 60s (if stationary detection is enabled) - the hardware motion sensor then wakes GPS when you start moving
- When exiting the zone, tracking automatically resumes
- Zone checks happen every location update with minimal overhead
- You can create unlimited geofence zones
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 eb5d5fee..1d57b866 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
@@ -46,6 +46,9 @@ class LocationForegroundService : Service() {
@Volatile private var serviceScope: CoroutineScope? = null
@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null
@Volatile private var locationRestartJob: Job? = null
+ @Volatile private var stationaryJob: Job? = null
+ @Volatile private var isStationary = false
+ @Volatile private var motionDetector: MotionDetector? = null
@Volatile private var insidePauseZone = false
@Volatile private var currentZoneName: String? = null
@Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null
@@ -57,6 +60,10 @@ class LocationForegroundService : Service() {
companion object {
private const val TAG = "LocationService"
+ /** Speed threshold below which the device is considered stationary (m/s). ~1 km/h */
+ private const val STATIONARY_SPEED_THRESHOLD = 0.3f
+ /** How long speed must stay below threshold before pausing GPS (ms). */
+ private const val STATIONARY_TIMEOUT_MS = 60_000L
const val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"
const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"
const val ACTION_FORCE_EXIT_ZONE = "com.Colota.FORCE_EXIT_ZONE"
@@ -96,8 +103,10 @@ class LocationForegroundService : Service() {
notificationHelper = NotificationHelper(this, notificationManager)
notificationHelper.createChannel()
+ motionDetector = MotionDetector(this) { onMotionDetected() }
+
AppLogger.enabled = dbHelper.getSetting("debug_mode_enabled")?.toBoolean() ?: false
- AppLogger.d(TAG, "Service created - provider: ${locationProvider.javaClass.simpleName}")
+ AppLogger.d(TAG, "Service created - provider: ${locationProvider.javaClass.simpleName}, motionSensor=${motionDetector?.isAvailable}")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -226,6 +235,8 @@ class LocationForegroundService : Service() {
override fun onDestroy() {
AppLogger.d(TAG, "Service destroyed")
+ motionDetector?.disarm()
+ stationaryJob?.cancel()
conditionMonitor.stop()
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -291,7 +302,6 @@ class LocationForegroundService : Service() {
locationUpdateCallback = null
}
-
private fun handleZoneRecheckAction() {
geofenceHelper.invalidateCache()
@@ -388,6 +398,12 @@ class LocationForegroundService : Service() {
}
+ applySpeedFallback(location)
+
+ // Evaluated before the distance filter so stationary detection works regardless
+ // of movement threshold - the distance filter is for recording quality, not motion state.
+ evaluateStationaryState(location)
+
// Software-side distance filter (FLP bypasses the OS-level distance filter for some fixes)
if (config.minUpdateDistance > 0f && prev != null) {
val distance = prev.distanceTo(location)
@@ -399,8 +415,6 @@ class LocationForegroundService : Service() {
AppLogger.d(TAG, "Location received: ${String.format(Locale.US, "%.5f, %.5f", location.latitude, location.longitude)} acc=${location.accuracy}m provider=${location.provider}")
- applySpeedFallback(location)
-
// After accuracy filter so bad GPS doesn't pollute speed average
profileManager.onLocationUpdate(location)
@@ -575,7 +589,8 @@ class LocationForegroundService : Service() {
lastSyncTime = if (offline) 0L else syncManager.lastSuccessfulSyncTime,
activeProfileName = profileManager.getActiveProfileName(),
forceUpdate = forceUpdate,
- isOfflineMode = offline
+ isOfflineMode = offline,
+ isStationary = isStationary
)
}
@@ -602,6 +617,87 @@ class LocationForegroundService : Service() {
stopSelf()
}
+ // ── Stationary detection ──────────────────────────────────────────────
+
+ /**
+ * Called from handleLocationUpdate to evaluate whether the device has
+ * become stationary. If speed stays below [STATIONARY_SPEED_THRESHOLD]
+ * for [STATIONARY_TIMEOUT_MS], active GPS is paused and the significant
+ * motion sensor is armed to wake it back up.
+ */
+ private fun evaluateStationaryState(location: android.location.Location) {
+ if (!config.pauseWhenStationary || motionDetector?.isAvailable != true) return
+
+ // Treat missing speed as 0 (stationary) - network/fused providers often omit speed
+ val speed = if (location.hasSpeed()) location.speed else 0f
+
+ if (speed >= STATIONARY_SPEED_THRESHOLD) {
+ // Moving - cancel any pending stationary timer
+ stationaryJob?.cancel()
+ stationaryJob = null
+ if (isStationary) {
+ resumeFromStationary()
+ }
+ return
+ }
+
+ // Speed below threshold - start countdown if not already running
+ if (!isStationary && stationaryJob?.isActive != true) {
+ stationaryJob = serviceScope?.launch {
+ delay(STATIONARY_TIMEOUT_MS)
+ withContext(Dispatchers.Main) {
+ enterStationary()
+ }
+ }
+ }
+ }
+
+ private fun enterStationary() {
+ if (isStationary) return
+ isStationary = true
+
+ AppLogger.i(TAG, "Device stationary - pausing active GPS, arming motion sensor")
+
+ // Stop active GPS but keep the service running
+ locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }
+ locationUpdateCallback = null
+
+ motionDetector?.arm()
+
+ val loc = lastKnownLocation
+ updateNotification(
+ lat = loc?.latitude,
+ lon = loc?.longitude,
+ forceUpdate = true
+ )
+ }
+
+ /** Called by MotionDetector when the device starts moving again. */
+ private fun onMotionDetected() {
+ if (!isStationary) return
+ AppLogger.i(TAG, "Motion detected - resuming active GPS")
+ resumeFromStationary()
+ }
+
+ private fun resumeFromStationary() {
+ isStationary = false
+ stationaryJob?.cancel()
+ stationaryJob = null
+ motionDetector?.disarm()
+
+ // Restart active GPS with current config
+ setupLocationUpdates()
+
+ val loc = lastKnownLocation
+ updateNotification(
+ lat = loc?.latitude,
+ lon = loc?.longitude,
+ forceUpdate = true
+ )
+ }
+
+ // ── Profile hot-swap ────────────────────────────────────────────────
+
/** Hot-swaps GPS interval and sync config on profile change. */
private fun applyProfileConfig(interval: Long, distance: Float, syncInterval: Int) {
config = config.copy(
@@ -612,6 +708,12 @@ class LocationForegroundService : Service() {
pushConfigToSyncManager()
+ // Resume from stationary if a profile switch happens (e.g. charging)
+ if (isStationary) {
+ resumeFromStationary()
+ return
+ }
+
// Synchronous restart on Main thread to avoid duplicate locations from
// the old listener firing during an async coroutine window.
locationRestartJob?.cancel()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/MotionDetector.kt b/apps/mobile/android/app/src/main/java/com/colota/service/MotionDetector.kt
new file mode 100644
index 00000000..ed224369
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/MotionDetector.kt
@@ -0,0 +1,71 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorManager
+import android.hardware.TriggerEvent
+import android.hardware.TriggerEventListener
+import com.Colota.util.AppLogger
+
+/**
+ * Detects device motion using the hardware significant motion sensor.
+ *
+ * The significant motion sensor is a one-shot trigger: it fires once when
+ * the device starts moving and then unregisters itself. After the callback
+ * fires, [rearm] must be called to listen for the next motion event.
+ *
+ * This is extremely battery-efficient because the detection runs entirely
+ * in hardware (the sensor hub), consuming near-zero power while idle.
+ *
+ * @param onMotionDetected Called on a sensor handler thread when motion is detected.
+ */
+class MotionDetector(
+ context: Context,
+ private val onMotionDetected: () -> Unit
+) {
+ companion object {
+ private const val TAG = "MotionDetector"
+ }
+
+ private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
+ private val motionSensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION)
+
+ @Volatile private var armed = false
+
+ private val triggerListener = object : TriggerEventListener() {
+ override fun onTrigger(event: TriggerEvent?) {
+ armed = false
+ AppLogger.d(TAG, "Significant motion detected")
+ onMotionDetected()
+ }
+ }
+
+ /** Whether the device has a significant motion sensor. */
+ val isAvailable: Boolean get() = motionSensor != null
+
+ /**
+ * Arms the sensor to fire on the next significant motion event.
+ * Safe to call multiple times - will not double-register.
+ */
+ fun arm() {
+ if (armed || motionSensor == null) return
+ val success = sensorManager.requestTriggerSensor(triggerListener, motionSensor)
+ armed = success
+ AppLogger.d(TAG, "Sensor armed: $success")
+ }
+
+ /**
+ * Disarms the sensor. Call when tracking stops or the feature is disabled.
+ */
+ fun disarm() {
+ if (!armed || motionSensor == null) return
+ sensorManager.cancelTriggerSensor(triggerListener, motionSensor)
+ armed = false
+ AppLogger.d(TAG, "Sensor disarmed")
+ }
+}
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 340b4302..de3242c5 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
@@ -105,9 +105,14 @@ class NotificationHelper(
lon: Double?,
queuedCount: Int,
lastSyncTime: Long,
- isOfflineMode: Boolean = false
+ isOfflineMode: Boolean = false,
+ isStationary: Boolean = false
): String = when {
isPaused -> "Paused: ${zoneName ?: "Unknown"}"
+ isStationary -> {
+ val coords = if (lat != null && lon != null) String.format(Locale.US, "%.5f, %.5f", lat, lon) else ""
+ if (coords.isNotEmpty()) "Stationary - $coords" else "Stationary - GPS paused"
+ }
lat != null && lon != null -> {
val coords = String.format(Locale.US, "%.5f, %.5f", lat, lon)
if (isOfflineMode) {
@@ -162,7 +167,8 @@ class NotificationHelper(
lastSyncTime: Long = 0L,
activeProfileName: String? = null,
forceUpdate: Boolean = false,
- isOfflineMode: Boolean = false
+ isOfflineMode: Boolean = false,
+ isStationary: Boolean = false
): Boolean {
val now = System.currentTimeMillis()
@@ -188,7 +194,7 @@ class NotificationHelper(
lastCoords = Pair(lat, lon)
}
- val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode)
+ val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode, isStationary)
// Dedup: skip if notification text hasn't changed
val cacheKey = "$statusText-$queuedCount-$activeProfileName"
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
index 279766b6..96995265 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
@@ -25,6 +25,7 @@ data class ServiceConfig(
val retryIntervalSeconds: Int = 30,
val isOfflineMode: Boolean = false,
val isWifiOnlySync: Boolean = false,
+ val pauseWhenStationary: Boolean = true,
val fieldMap: String? = null,
val customFields: String? = null,
val httpMethod: String = "POST"
@@ -44,6 +45,7 @@ data class ServiceConfig(
retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 30,
isOfflineMode = saved["isOfflineMode"]?.toBoolean() ?: false,
isWifiOnlySync = saved["isWifiOnlySync"]?.toBoolean() ?: false,
+ pauseWhenStationary = saved["pauseWhenStationary"]?.toBoolean() ?: true,
fieldMap = saved["fieldMap"],
customFields = saved["customFields"],
httpMethod = saved["httpMethod"] ?: "POST"
@@ -84,6 +86,7 @@ data class ServiceConfig(
retryIntervalSeconds = config.getIntOrNull("retryInterval") ?: dbConfig.retryIntervalSeconds,
isOfflineMode = config.getBooleanOrNull("isOfflineMode") ?: dbConfig.isOfflineMode,
isWifiOnlySync = config.getBooleanOrNull("isWifiOnlySync") ?: dbConfig.isWifiOnlySync,
+ pauseWhenStationary = config.getBooleanOrNull("pauseWhenStationary") ?: dbConfig.pauseWhenStationary,
fieldMap = fieldMapJson ?: dbConfig.fieldMap,
customFields = customFieldsJson ?: dbConfig.customFields,
httpMethod = config.getStringOrNull("httpMethod") ?: dbConfig.httpMethod
@@ -105,6 +108,7 @@ data class ServiceConfig(
retryIntervalSeconds = extras.getIntOrDefault("retryInterval", dbConfig.retryIntervalSeconds),
isOfflineMode = extras.getBooleanOrDefault("isOfflineMode", dbConfig.isOfflineMode),
isWifiOnlySync = extras.getBooleanOrDefault("isWifiOnlySync", dbConfig.isWifiOnlySync),
+ pauseWhenStationary = extras.getBooleanOrDefault("pauseWhenStationary", dbConfig.pauseWhenStationary),
fieldMap = extras.getStringOrDefault("fieldMap", dbConfig.fieldMap),
customFields = extras.getStringOrDefault("customFields", dbConfig.customFields),
httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST"
@@ -124,6 +128,7 @@ data class ServiceConfig(
putExtra("retryInterval", retryIntervalSeconds)
putExtra("isOfflineMode", isOfflineMode)
putExtra("isWifiOnlySync", isWifiOnlySync)
+ putExtra("pauseWhenStationary", pauseWhenStationary)
fieldMap?.let { putExtra("fieldMap", it) }
customFields?.let { putExtra("customFields", it) }
putExtra("httpMethod", httpMethod)
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 2f3b8ad8..fb1d237f 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
@@ -1245,6 +1245,219 @@ class LocationForegroundServiceTest {
method.invoke(service, geofence)
}
+ // =========================================================================
+ // evaluateStationaryState - motion detection
+ // =========================================================================
+
+ @Test
+ fun `evaluateStationaryState skips when pauseWhenStationary is disabled`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ pauseWhenStationary = false,
+ filterInaccurateLocations = true,
+ accuracyThreshold = 50.0f
+ ))
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ every { motionDetector.isAvailable } returns true
+ setField("motionDetector", motionDetector)
+
+ val location = mockLocation(speed = 0.1f)
+ invokeEvaluateStationaryState(location)
+
+ val stationaryJob: Job? = getField("stationaryJob")
+ assertNull("Should not start stationary timer when disabled", stationaryJob)
+ }
+
+ @Test
+ fun `evaluateStationaryState skips when motion sensor unavailable`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ pauseWhenStationary = true,
+ filterInaccurateLocations = true,
+ accuracyThreshold = 50.0f
+ ))
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ every { motionDetector.isAvailable } returns false
+ setField("motionDetector", motionDetector)
+
+ val location = mockLocation(speed = 0.1f)
+ invokeEvaluateStationaryState(location)
+
+ val stationaryJob: Job? = getField("stationaryJob")
+ assertNull("Should not start timer when sensor unavailable", stationaryJob)
+ }
+
+ @Test
+ fun `evaluateStationaryState starts timer when inside pause zone`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ pauseWhenStationary = true,
+ filterInaccurateLocations = true,
+ accuracyThreshold = 50.0f
+ ))
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ every { motionDetector.isAvailable } returns true
+ setField("motionDetector", motionDetector)
+ setField("insidePauseZone", true)
+
+ val location = mockLocation(speed = 0.1f)
+ invokeEvaluateStationaryState(location)
+
+ val stationaryJob: Job? = getField("stationaryJob")
+ assertNotNull("Should start timer inside pause zone - GPS still running there", stationaryJob)
+ }
+
+ @Test
+ fun `evaluateStationaryState starts timer when speed below threshold`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ pauseWhenStationary = true,
+ filterInaccurateLocations = true,
+ accuracyThreshold = 50.0f
+ ))
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ every { motionDetector.isAvailable } returns true
+ setField("motionDetector", motionDetector)
+
+ val location = mockLocation(speed = 0.1f) // below 0.3 m/s threshold
+ invokeEvaluateStationaryState(location)
+
+ val stationaryJob: Job? = getField("stationaryJob")
+ assertNotNull("Should start stationary timer", stationaryJob)
+ assertTrue("Timer should be active", stationaryJob!!.isActive)
+ }
+
+ @Test
+ fun `evaluateStationaryState cancels timer when speed above threshold`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ pauseWhenStationary = true,
+ filterInaccurateLocations = true,
+ accuracyThreshold = 50.0f
+ ))
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ every { motionDetector.isAvailable } returns true
+ setField("motionDetector", motionDetector)
+
+ // First: trigger timer with low speed
+ val slowLocation = mockLocation(speed = 0.1f)
+ invokeEvaluateStationaryState(slowLocation)
+ val job: Job? = getField("stationaryJob")
+ assertNotNull("Timer should exist", job)
+
+ // Then: cancel with movement
+ val fastLocation = mockLocation(speed = 5.0f)
+ invokeEvaluateStationaryState(fastLocation)
+ val cancelledJob: Job? = getField("stationaryJob")
+ assertNull("Timer should be cancelled", cancelledJob)
+ }
+
+ @Test
+ fun `evaluateStationaryState treats missing speed as stationary`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ pauseWhenStationary = true,
+ filterInaccurateLocations = true,
+ accuracyThreshold = 50.0f
+ ))
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ every { motionDetector.isAvailable } returns true
+ setField("motionDetector", motionDetector)
+
+ val location = mockLocation(hasSpeed = false)
+ invokeEvaluateStationaryState(location)
+
+ val stationaryJob: Job? = getField("stationaryJob")
+ assertNotNull("Should start stationary timer when speed is missing", stationaryJob)
+ }
+
+ @Test
+ fun `enterStationary stops location updates and arms motion sensor`() = testScope.runTest {
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ setField("motionDetector", motionDetector)
+
+ val callback = mockk<LocationUpdateCallback>(relaxed = true)
+ setField("locationUpdateCallback", callback)
+
+ invokeEnterStationary()
+
+ assertTrue(getField<Boolean>("isStationary"))
+ verify { locationProvider.removeLocationUpdates(callback) }
+ verify { motionDetector.arm() }
+ assertNull(getField<LocationUpdateCallback?>("locationUpdateCallback"))
+ }
+
+ @Test
+ fun `enterStationary arms sensor when inside pause zone`() = testScope.runTest {
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ setField("motionDetector", motionDetector)
+ setField("insidePauseZone", true)
+
+ invokeEnterStationary()
+
+ assertTrue(getField<Boolean>("isStationary"))
+ verify { motionDetector.arm() }
+ }
+
+ @Test
+ fun `onMotionDetected resumes GPS when stationary`() = testScope.runTest {
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ setField("motionDetector", motionDetector)
+ setField("isStationary", true)
+
+ invokeOnMotionDetected()
+
+ assertFalse(getField<Boolean>("isStationary"))
+ verify { motionDetector.disarm() }
+ }
+
+ @Test
+ fun `onMotionDetected ignores when not stationary`() = testScope.runTest {
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ setField("motionDetector", motionDetector)
+ setField("isStationary", false)
+
+ invokeOnMotionDetected()
+
+ verify(exactly = 0) { motionDetector.disarm() }
+ }
+
+ @Test
+ fun `applyProfileConfig resumes from stationary`() = testScope.runTest {
+ val motionDetector = mockk<MotionDetector>(relaxed = true)
+ setField("motionDetector", motionDetector)
+ setField("isStationary", true)
+
+ invokeApplyProfileConfig(10000L, 5.0f, 300)
+
+ assertFalse(getField<Boolean>("isStationary"))
+ verify { motionDetector.disarm() }
+ }
+
+ // =========================================================================
+ // Reflection helpers
+ // =========================================================================
+
+ private fun invokeEvaluateStationaryState(location: Location) {
+ val method = LocationForegroundService::class.java.getDeclaredMethod(
+ "evaluateStationaryState", Location::class.java
+ )
+ method.isAccessible = true
+ method.invoke(service, location)
+ }
+
+ private fun invokeEnterStationary() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("enterStationary")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
+ private fun invokeOnMotionDetected() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("onMotionDetected")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
private fun geofence(name: String, lat: Double = 52.52, lon: Double = 13.405, radius: Double = 100.0) =
GeofenceHelper.CachedGeofence(name, lat, lon, radius)
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/MotionDetectorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/MotionDetectorTest.kt
new file mode 100644
index 00000000..c25b15be
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/MotionDetectorTest.kt
@@ -0,0 +1,101 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorManager
+import android.hardware.TriggerEventListener
+import io.mockk.*
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+class MotionDetectorTest {
+
+ private lateinit var context: Context
+ private lateinit var sensorManager: SensorManager
+ private lateinit var motionSensor: Sensor
+ private var motionCallback = 0
+
+ private fun makeDetector(sensorAvailable: Boolean = true): MotionDetector {
+ context = mockk()
+ sensorManager = mockk(relaxed = true)
+ motionSensor = mockk()
+
+ every { context.getSystemService(Context.SENSOR_SERVICE) } returns sensorManager
+ every { sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION) } returns
+ if (sensorAvailable) motionSensor else null
+ every { sensorManager.requestTriggerSensor(any(), any()) } returns true
+
+ motionCallback = 0
+ return MotionDetector(context) { motionCallback++ }
+ }
+
+ @Test
+ fun `isAvailable returns true when sensor exists`() {
+ val detector = makeDetector(sensorAvailable = true)
+ assertTrue(detector.isAvailable)
+ }
+
+ @Test
+ fun `isAvailable returns false when sensor missing`() {
+ val detector = makeDetector(sensorAvailable = false)
+ assertFalse(detector.isAvailable)
+ }
+
+ @Test
+ fun `arm registers trigger sensor`() {
+ val detector = makeDetector()
+ detector.arm()
+ verify(exactly = 1) { sensorManager.requestTriggerSensor(any(), motionSensor) }
+ }
+
+ @Test
+ fun `arm does nothing when sensor unavailable`() {
+ val detector = makeDetector(sensorAvailable = false)
+ detector.arm()
+ verify(exactly = 0) { sensorManager.requestTriggerSensor(any(), any()) }
+ }
+
+ @Test
+ fun `arm does not double-register when already armed`() {
+ val detector = makeDetector()
+ detector.arm()
+ detector.arm()
+ verify(exactly = 1) { sensorManager.requestTriggerSensor(any(), motionSensor) }
+ }
+
+ @Test
+ fun `disarm cancels trigger sensor`() {
+ val detector = makeDetector()
+ detector.arm()
+ detector.disarm()
+ verify(exactly = 1) { sensorManager.cancelTriggerSensor(any(), motionSensor) }
+ }
+
+ @Test
+ fun `disarm does nothing when not armed`() {
+ val detector = makeDetector()
+ detector.disarm()
+ verify(exactly = 0) { sensorManager.cancelTriggerSensor(any(), any()) }
+ }
+
+ @Test
+ fun `onTrigger invokes callback and resets armed state`() {
+ val detector = makeDetector()
+ val listenerSlot = slot<TriggerEventListener>()
+ every { sensorManager.requestTriggerSensor(capture(listenerSlot), any()) } returns true
+
+ detector.arm()
+ listenerSlot.captured.onTrigger(null)
+
+ assertEquals(1, motionCallback)
+ // After trigger fires, armed should be false - disarm should not call cancel
+ detector.disarm()
+ verify(exactly = 0) { sensorManager.cancelTriggerSensor(any(), any()) }
+ }
+}
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 b3d4a965..cacdb201 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
@@ -214,6 +214,41 @@ class NotificationHelperTest {
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)
+ }
+
// --- Reflection helper ---
private fun setField(name: String, value: Any?) {
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
index bf7c8143..d6b08637 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ServiceConfigTest.kt
@@ -217,6 +217,7 @@ class ServiceConfigTest {
every { getInt("retryInterval") } returns 60
every { getBoolean("isOfflineMode") } returns true
every { getBoolean("isWifiOnlySync") } returns true
+ every { getBoolean("pauseWhenStationary") } returns false
every { getString("fieldMap") } returns """{"lat":"latitude"}"""
every { getString("customFields") } returns """{"_type":"location"}"""
every { getString("httpMethod") } returns "GET"
@@ -237,6 +238,7 @@ class ServiceConfigTest {
assertEquals(60, config.retryIntervalSeconds)
assertTrue(config.isOfflineMode)
assertTrue(config.isWifiOnlySync)
+ assertFalse(config.pauseWhenStationary)
assertEquals("""{"lat":"latitude"}""", config.fieldMap)
assertEquals("GET", config.httpMethod)
}
diff --git a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
index ac05dae6..865d32e3 100644
--- a/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
+++ b/apps/mobile/src/components/features/settings/SyncStrategySettings.tsx
@@ -192,6 +192,21 @@ export function SyncStrategySettings({
hint="Only record if moved more than this distance"
colors={colors}
/>
+
+ <SettingRow
+ label="Pause GPS when stationary"
+ hint="Stops active GPS after 60s without movement and resumes on motion"
+ >
+ <Switch
+ value={settings.pauseWhenStationary}
+ onValueChange={(value) => onImmediateSave({ ...settings, pauseWhenStationary: value })}
+ trackColor={{
+ false: colors.border,
+ true: colors.primary + "80"
+ }}
+ thumbColor={settings.pauseWhenStationary ? colors.primary : colors.border}
+ />
+ </SettingRow>
</View>
{!settings.isOfflineMode && (
diff --git a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
index 5892d210..7c9123a6 100644
--- a/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/SyncStrategySettings.test.tsx
@@ -243,7 +243,8 @@ describe("SyncStrategySettings", () => {
fireEvent.press(getByText("+ Show Advanced Settings"))
- const retrySwitch = getAllByRole("switch")[0]
+ // Retry Failed Uploads is the second switch (after Pause GPS when stationary)
+ const retrySwitch = getAllByRole("switch")[1]
fireEvent(retrySwitch, "valueChange", true)
@@ -261,7 +262,8 @@ describe("SyncStrategySettings", () => {
fireEvent.press(getByText("+ Show Advanced Settings"))
- const retrySwitch = getAllByRole("switch")[0]
+ // Retry Failed Uploads is the second switch (after Pause GPS when stationary)
+ const retrySwitch = getAllByRole("switch")[1]
fireEvent(retrySwitch, "valueChange", false)
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index a7ddb992..21b655c0 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -54,6 +54,7 @@ function parseRawSettings(allRaw: Record<string, string>): Settings {
isOfflineMode: allRaw.isOfflineMode === "true",
isWifiOnlySync: allRaw.isWifiOnlySync === "true",
+ pauseWhenStationary: allRaw.pauseWhenStationary !== "false",
endpoint: allRaw.endpoint ?? DEFAULT_SETTINGS.endpoint,
syncPreset: (allRaw.syncPreset as any) ?? DEFAULT_SETTINGS.syncPreset,
filterInaccurateLocations: allRaw.filterInaccurateLocations === "true",
diff --git a/apps/mobile/src/services/SettingsService.ts b/apps/mobile/src/services/SettingsService.ts
index d15a0dbe..d4ca6651 100644
--- a/apps/mobile/src/services/SettingsService.ts
+++ b/apps/mobile/src/services/SettingsService.ts
@@ -50,6 +50,7 @@ export const SettingsService = {
case "filterInaccurateLocations":
case "isOfflineMode":
case "isWifiOnlySync":
+ case "pauseWhenStationary":
// Boolean → "true"/"false"
stringValue = String(value)
break
diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
index 848a6d33..16c1675c 100644
--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts
@@ -118,7 +118,8 @@ describe("NativeLocationService", () => {
apiTemplate: "custom" as const,
syncPreset: "instant" as const,
httpMethod: "POST" as const,
- hasCompletedSetup: false
+ hasCompletedSetup: false,
+ pauseWhenStationary: true
}
await NativeLocationService.start(settings)
@@ -149,7 +150,8 @@ describe("NativeLocationService", () => {
apiTemplate: "traccar" as const,
syncPreset: "instant" as const,
httpMethod: "GET" as const,
- hasCompletedSetup: false
+ hasCompletedSetup: false,
+ pauseWhenStationary: true
}
await NativeLocationService.start(settings)
diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.ts
index f367936d..6e6a2970 100644
--- a/apps/mobile/src/types/global.ts
+++ b/apps/mobile/src/types/global.ts
@@ -289,6 +289,7 @@ export interface Settings {
maxRetries: number
isOfflineMode: boolean
isWifiOnlySync: boolean
+ pauseWhenStationary: boolean
// UI State
syncPreset: SyncPreset
@@ -310,6 +311,7 @@ export const DEFAULT_SETTINGS: Settings = {
maxRetries: 5,
isOfflineMode: false,
isWifiOnlySync: false,
+ pauseWhenStationary: true,
hasCompletedSetup: false,
httpMethod: "POST"
} as const