Skip to content

Colota - Android GPS Location tracker

feat: add entry delay on geofence entry for reliable arrival detection (#236)

Max Dietrich3dd40f405570
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 27ec03c3..03c07d5c 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -26,19 +26,19 @@ import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
## How It Works
- 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]"
+- 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 notification shows "Paused: [Zone Name]" once the pause takes effect
- 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
+- If you leave before the entry delay completes, the delay is cancelled and tracking continues uninterrupted
+- 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. Stationary detection is suspended during the entry delay so arrival points keep being logged even if you stop moving on arrival
- When exiting the zone, tracking automatically resumes
- Zone checks happen every location update with minimal overhead
- You can create unlimited geofence zones
## Anchor Points
-When you enter or exit a pause zone, Colota saves a synthetic location at the geofence center. This gives your tracks clean start and end points instead of starting or ending mid-road.
+When you exit a pause zone, Colota saves a synthetic location at the geofence center. This gives your new trip a clean start point at the zone center rather than somewhere mid-road where GPS first locks in.
-- **On enter:** An anchor point is logged at the zone center, then recording pauses
-- **On exit:** Recording resumes and an anchor point is logged at the zone center
+- **On exit:** An anchor point is logged at the zone center, then recording resumes
Anchor points use the geofence center coordinates (not your actual GPS position) and set accuracy to the zone radius. They are saved to the database and synced to your server like regular locations.
diff --git a/apps/docs/docs/integrations/geopulse.md b/apps/docs/docs/integrations/geopulse.md
index 90fe6cec..18c95451 100644
--- a/apps/docs/docs/integrations/geopulse.md
+++ b/apps/docs/docs/integrations/geopulse.md
@@ -53,4 +53,8 @@ The GeoPulse template uses Colota's default field names with no custom fields:
| `tst` | `tst` | Unix timestamp |
| `bear` | `bear` | Bearing (degrees) |
+## Geofence Compatibility
+
+GeoPulse needs multiple points clustered at your arrival location to confirm a trip has ended there - a single point is indistinguishable from a brief stop at a traffic light. Colota handles this automatically: when you enter a pause zone, it keeps logging real GPS points for 3.5× your tracking interval before pausing, producing several arrival points for GeoPulse to finalize trip arrival.
+
Note: GeoPulse also supports OwnTracks as a location source. If you prefer, you can use the OwnTracks template with the endpoint `https://geopulse.yourdomain.com/api/owntracks` instead.
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 1d57b866..1b0b5c5a 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
@@ -53,6 +53,8 @@ class LocationForegroundService : Service() {
@Volatile private var currentZoneName: String? = null
@Volatile private var currentZoneGeofence: GeofenceHelper.CachedGeofence? = null
@Volatile private var lastKnownLocation: android.location.Location? = null
+ @Volatile private var entryDelayJob: Job? = null
+ @Volatile private var pendingPauseZone: GeofenceHelper.CachedGeofence? = null
@Volatile private lateinit var config: ServiceConfig
@Volatile private var fieldMap: Map<String, String>? = null
@@ -64,9 +66,10 @@ class LocationForegroundService : Service() {
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
+ /** Multiplier applied to the tracking interval for the geofence entry delay. */
+ private const val ENTRY_DELAY_MULTIPLIER = 3.5
const val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"
const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"
- const val ACTION_FORCE_EXIT_ZONE = "com.Colota.FORCE_EXIT_ZONE"
const val ACTION_REFRESH_NOTIFICATION = "com.Colota.REFRESH_NOTIFICATION"
const val ACTION_RECHECK_PROFILES = "com.Colota.RECHECK_PROFILES"
@@ -74,7 +77,6 @@ class LocationForegroundService : Service() {
private val LIGHTWEIGHT_ACTIONS = setOf(
ACTION_MANUAL_FLUSH,
ACTION_RECHECK_ZONE,
- ACTION_FORCE_EXIT_ZONE,
ACTION_REFRESH_NOTIFICATION,
ACTION_RECHECK_PROFILES
)
@@ -137,7 +139,7 @@ class LocationForegroundService : Service() {
loadConfigFromIntent(null)
}
- // Restore pause zone state so restarts don't trigger duplicate anchor points
+ // Restore pause zone state so a restart without a cached location fix doesn't incorrectly resume tracking
if (!insidePauseZone) {
val savedZone = savedSettings["pause_zone_name"]
if (!savedZone.isNullOrBlank()) {
@@ -182,14 +184,6 @@ class LocationForegroundService : Service() {
)
return START_STICKY
}
- ACTION_FORCE_EXIT_ZONE -> {
- if (insidePauseZone) {
- AppLogger.d(TAG, "Force exit from zone: $currentZoneName")
- exitPauseZone()
- lastKnownLocation?.let { recheckZoneWithLocation(it) }
- }
- return START_STICKY
- }
ACTION_RECHECK_ZONE -> {
handleZoneRecheckAction()
return START_STICKY
@@ -237,6 +231,9 @@ class LocationForegroundService : Service() {
motionDetector?.disarm()
stationaryJob?.cancel()
+ entryDelayJob?.cancel()
+ entryDelayJob = null
+ pendingPauseZone = null
conditionMonitor.stop()
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -336,32 +333,39 @@ class LocationForegroundService : Service() {
private fun recheckZoneWithLocation(location: android.location.Location) {
val zone = geofenceHelper.getPauseZone(location)
+ applyZoneTransition(zone)
+
+ // Same zone - refresh notification coords
+ if (zone != null && insidePauseZone && zone.name == currentZoneName) {
+ updateNotification(
+ lat = location.latitude,
+ lon = location.longitude,
+ pausedInZone = true,
+ zoneName = currentZoneName,
+ forceUpdate = true
+ )
+ } else if (zone == null && !insidePauseZone && pendingPauseZone == null) {
+ updateNotification(
+ location.latitude,
+ location.longitude,
+ forceUpdate = true
+ )
+ }
+ }
- when {
+ /**
+ * Applies zone entry/exit state transitions common to both live location updates
+ * and manual zone rechecks. Returns the anchor [Job] if a zone exit was triggered.
+ */
+ private fun applyZoneTransition(zone: GeofenceHelper.CachedGeofence?): Job? {
+ return when {
zone != null && (!insidePauseZone || zone.name != currentZoneName) -> {
- enterPauseZone(zone)
- }
- zone == null && insidePauseZone -> {
- exitPauseZone()
- }
- // Same zone - refresh notification coords
- zone != null && insidePauseZone && zone.name == currentZoneName -> {
- updateNotification(
- lat = location.latitude,
- lon = location.longitude,
- pausedInZone = true,
- zoneName = currentZoneName,
- forceUpdate = true
- )
- }
-
- else -> {
- updateNotification(
- location.latitude,
- location.longitude,
- forceUpdate = true
- )
+ if (pendingPauseZone?.name != zone.name) startEntryDelay(zone)
+ null
}
+ zone == null && pendingPauseZone != null -> { cancelEntryDelay(); null }
+ zone == null && insidePauseZone -> exitPauseZone()
+ else -> null
}
}
@@ -405,7 +409,8 @@ class LocationForegroundService : Service() {
evaluateStationaryState(location)
// Software-side distance filter (FLP bypasses the OS-level distance filter for some fixes)
- if (config.minUpdateDistance > 0f && prev != null) {
+ // Bypassed during geofence entry delay so stationary arrival points are logged
+ if (pendingPauseZone == null && config.minUpdateDistance > 0f && prev != null) {
val distance = prev.distanceTo(location)
if (distance < config.minUpdateDistance) {
AppLogger.d(TAG, "Location filtered: distance ${String.format(Locale.US, "%.1f", distance)}m < threshold ${config.minUpdateDistance}m")
@@ -421,15 +426,8 @@ class LocationForegroundService : Service() {
lastKnownLocation = location
val zone = geofenceHelper.getPauseZone(location)
- var anchorJob: Job? = null
- when {
- zone != null && (!insidePauseZone || zone.name != currentZoneName) -> {
- enterPauseZone(zone)
- return
- }
- zone == null && insidePauseZone -> anchorJob = exitPauseZone()
- zone != null && insidePauseZone -> return
- }
+ if (zone != null && insidePauseZone && zone.name == currentZoneName) return
+ val anchorJob = applyZoneTransition(zone)
val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()
@@ -476,11 +474,50 @@ class LocationForegroundService : Service() {
}
}
- private fun enterPauseZone(geofence: GeofenceHelper.CachedGeofence) {
- if (!insidePauseZone) {
- saveAnchorPoint(geofence)
+ /**
+ * Starts a delay of 3.5 tracking intervals before pausing GPS on geofence entry.
+ * Real GPS locations continue to be logged during the delay, giving backends
+ * like GeoPulse enough arrival points for reliable trip detection.
+ * If the device exits the zone before the delay completes, the delay is cancelled.
+ */
+ private fun startEntryDelay(geofence: GeofenceHelper.CachedGeofence) {
+ entryDelayJob?.cancel()
+ stationaryJob?.cancel()
+ stationaryJob = null
+ pendingPauseZone = geofence
+
+ val scope = serviceScope ?: run {
+ AppLogger.w(TAG, "Cannot start entry delay for '${geofence.name}' - service scope is null")
+ pendingPauseZone = null
+ return
}
+ val delayMs = (config.interval * ENTRY_DELAY_MULTIPLIER).toLong()
+ AppLogger.d(TAG, "Geofence entry delay started for '${geofence.name}': ${delayMs}ms (${delayMs / 1000.0}s)")
+
+ entryDelayJob = scope.launch {
+ delay(delayMs)
+ withContext(Dispatchers.Main) {
+ if (pendingPauseZone?.name == geofence.name) {
+ pendingPauseZone = null
+ enterPauseZone(geofence)
+ }
+ }
+ }
+ }
+
+ private fun cancelEntryDelay() {
+ entryDelayJob?.cancel()
+ entryDelayJob = null
+ val zone = pendingPauseZone
+ pendingPauseZone = null
+ AppLogger.d(TAG, "Entry delay cancelled - left zone '${zone?.name}' before delay completed")
+
+ val loc = lastKnownLocation
+ updateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)
+ }
+
+ private fun enterPauseZone(geofence: GeofenceHelper.CachedGeofence) {
insidePauseZone = true
currentZoneName = geofence.name
currentZoneGeofence = geofence
@@ -521,7 +558,7 @@ class LocationForegroundService : Service() {
return anchorJob
}
- /** Logs a synthetic location at the geofence center for clean track start/end points. */
+ /** Logs a synthetic location at the geofence center on zone exit to give the departing trip a clean start point. */
private fun saveAnchorPoint(geofence: GeofenceHelper.CachedGeofence): Job? {
if (!::config.isInitialized) {
AppLogger.w(TAG, "Config not yet initialized, skipping anchor point for '${geofence.name}'")
@@ -627,6 +664,7 @@ class LocationForegroundService : Service() {
*/
private fun evaluateStationaryState(location: android.location.Location) {
if (!config.pauseWhenStationary || motionDetector?.isAvailable != true) return
+ if (pendingPauseZone != null) return // keep GPS running until arrival points are logged
// Treat missing speed as 0 (stationary) - network/fused providers often omit speed
val speed = if (location.hasSpeed()) location.speed else 0f
@@ -718,6 +756,7 @@ class LocationForegroundService : Service() {
// the old listener firing during an async coroutine window.
locationRestartJob?.cancel()
locationRestartJob = null
+ if (pendingPauseZone != null) cancelEntryDelay()
stopLocationUpdates()
setupLocationUpdates()
@@ -762,52 +801,11 @@ class LocationForegroundService : Service() {
if (it.isNotBlank()) customFields = payloadBuilder.parseCustomFields(it)
}
- if (AppLogger.enabled) {
- val batteryStatusStr = deviceInfoHelper.getBatteryStatusString()
-
- AppLogger.d(TAG, """
- ╔════════════════════════════════════════════════════════════════╗
- ║ COLOTA LOCATION SERVICE CONFIGURATION ║
- ╠════════════════════════════════════════════════════════════════╣
- ║ GPS TRACKING ║
- ╟────────────────────────────────────────────────────────────────╢
- ║ Update Interval: ${config.interval}ms (${config.interval/1000.0}s)
- ║ Min Update Distance: ${config.minUpdateDistance}m
- ║ Accuracy Threshold: ${config.accuracyThreshold}m
- ║ Filter Inaccurate: ${config.filterInaccurateLocations}
- ╟────────────────────────────────────────────────────────────────╢
- ║ NETWORK & SYNC ║
- ╟────────────────────────────────────────────────────────────────╢
- ║ Endpoint: ${if(config.endpoint.isBlank()) "⚠️ NOT CONFIGURED" else "✓ ${config.endpoint}"}
- ║ Offline Mode: ${if(config.isOfflineMode) "✓ ENABLED" else "✗ Disabled"}
- ║ Sync Mode: ${if(config.syncIntervalSeconds == 0) "⚡ INSTANT SEND" else "🕐 PERIODIC (${config.syncIntervalSeconds}s)"}
- ║ Retry Interval: ${config.retryIntervalSeconds}s
- ║ Max Retry Attempts: ${config.maxRetries}
- ╟────────────────────────────────────────────────────────────────╢
- ║ PERFORMANCE OPTIMIZATION ║
- ╟────────────────────────────────────────────────────────────────╢
- ║ Battery Check Cache: 60s (managed by DeviceInfoHelper)
- ║ Notification Throttle: ${NotificationHelper.THROTTLE_MS/1000}s
- ╟────────────────────────────────────────────────────────────────╢
- ║ FIELD MAPPING ║
- ╟────────────────────────────────────────────────────────────────╢
- ║ Custom Fields: ${if(fieldMap != null && fieldMap!!.isNotEmpty()) "✓ YES (${fieldMap!!.size} mappings)" else "✗ Using Defaults"}
- ${if(fieldMap != null && fieldMap!!.isNotEmpty()) {
- fieldMap!!.entries.joinToString("\n") {
- "║ ${it.key.padEnd(20)} → ${it.value}"
- }
- } else ""}
- ╟────────────────────────────────────────────────────────────────╢
- ║ CURRENT SERVICE STATE ║
- ╟────────────────────────────────────────────────────────────────╢
- ║ Tracking Status: ✓ ACTIVE
- ║ Pause Zone: ${if(insidePauseZone) "⏸️ PAUSED in '$currentZoneName'" else "✓ Not in zone"}
- ║ Battery Level: $batteryStatusStr
- ║ Queued Locations: ${syncManager.getCachedQueuedCount()} items
- ║ Last Sync: ${notificationHelper.formatTimeSinceSync(syncManager.lastSuccessfulSyncTime)}
- ║ Last Location: ${if(lastKnownLocation != null) String.format(Locale.US, "%.5f, %.5f", lastKnownLocation!!.latitude, lastKnownLocation!!.longitude) else "N/A"}
- ╚════════════════════════════════════════════════════════════════╝
- """.trimIndent())
- }
+ AppLogger.d(TAG, buildString {
+ append("Config loaded: interval=${config.interval}ms, distance=${config.minUpdateDistance}m, accuracy=${config.accuracyThreshold}m")
+ append(", endpoint=${if (config.endpoint.isBlank()) "NOT CONFIGURED" else config.endpoint}")
+ append(", offline=${config.isOfflineMode}, sync=${if (config.syncIntervalSeconds == 0) "instant" else "${config.syncIntervalSeconds}s"}")
+ if (!fieldMap.isNullOrEmpty()) append(", fieldMap=${fieldMap!!.size} mappings")
+ })
}
}
\ No newline at end of file
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 fb1d237f..2a59012c 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
@@ -431,28 +431,20 @@ class LocationForegroundServiceTest {
}
@Test
- fun `handleLocationUpdate enters pause zone when location is in geofence`() = testScope.runTest {
+ fun `handleLocationUpdate starts entry delay when location enters geofence`() = testScope.runTest {
every { geofenceHelper.getPauseZone(any()) } returns homeGeofence
val location = mockLocation()
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
invokeHandleLocationUpdate(location)
- assertTrue(getField("insidePauseZone"))
- assertEquals("Home", getField<String?>("currentZoneName"))
- verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }
- // Anchor point is saved at geofence center, but regular GPS location is not saved
- verify(exactly = 1) { dbHelper.saveLocation(
- latitude = homeGeofence.lat,
- longitude = homeGeofence.lon,
- accuracy = homeGeofence.radius,
- altitude = null,
- speed = null,
- bearing = null,
- battery = any(),
- battery_status = any(),
- timestamp = any(),
- endpoint = any()
- ) }
+ // Entry delay pending - not yet inside zone
+ assertFalse(getField("insidePauseZone"))
+ assertEquals(homeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ // GPS location is saved during the delay window
+ verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ // Zone event not sent until delay completes
+ verify(exactly = 0) { LocationServiceModule.sendPauseZoneEvent(true, any()) }
}
@Test
@@ -469,20 +461,20 @@ class LocationForegroundServiceTest {
}
@Test
- fun `handleLocationUpdate updates zone when moving to different zone`() = testScope.runTest {
+ fun `handleLocationUpdate starts entry delay when moving between zones`() = testScope.runTest {
setField("insidePauseZone", true)
setField("currentZoneName", "Home")
setField("currentZoneGeofence", homeGeofence)
every { geofenceHelper.getPauseZone(any()) } returns officeGeofence
val location = mockLocation()
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
invokeHandleLocationUpdate(location)
+ // Still in Home until delay fires
assertTrue(getField("insidePauseZone"))
- assertEquals("Office", getField<String?>("currentZoneName"))
- assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("currentZoneGeofence"))
- // No anchor saved for zone-to-zone transition
- verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ assertEquals("Home", getField<String?>("currentZoneName"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@Test
@@ -555,7 +547,7 @@ class LocationForegroundServiceTest {
// =========================================================================
@Test
- fun `ACTION_FORCE_EXIT_ZONE rechecks zone after forced exit`() {
+ fun `exitPauseZone followed by recheck clears zone when location outside`() {
setField("insidePauseZone", true)
setField("currentZoneName", "Office")
setField("currentZoneGeofence", officeGeofence)
@@ -570,7 +562,7 @@ class LocationForegroundServiceTest {
}
@Test
- fun `ACTION_FORCE_EXIT_ZONE re-enters if still in zone after recheck`() {
+ fun `exitPauseZone followed by recheck starts delay when still in zone`() {
setField("insidePauseZone", true)
setField("currentZoneName", "Office")
setField("currentZoneGeofence", officeGeofence)
@@ -581,12 +573,12 @@ class LocationForegroundServiceTest {
invokeExitPauseZone()
invokeRecheckZoneWithLocation(location)
- assertTrue(getField("insidePauseZone"))
- assertEquals("Office", getField<String?>("currentZoneName"))
+ assertFalse(getField("insidePauseZone"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@Test
- fun `ACTION_RECHECK_ZONE with fresh location rechecks immediately`() {
+ fun `ACTION_RECHECK_ZONE with fresh location starts entry delay`() {
val freshLocation = mockLocation(time = System.currentTimeMillis())
setField("lastKnownLocation", freshLocation)
every { geofenceHelper.getPauseZone(freshLocation) } returns parkGeofence
@@ -594,8 +586,8 @@ class LocationForegroundServiceTest {
invokeHandleZoneRecheckAction()
verify { geofenceHelper.invalidateCache() }
- assertTrue(getField("insidePauseZone"))
- assertEquals("Park", getField<String?>("currentZoneName"))
+ assertFalse(getField("insidePauseZone"))
+ assertEquals(parkGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@Test
@@ -686,35 +678,13 @@ class LocationForegroundServiceTest {
}
@Test
- fun `enterPauseZone saves anchor point at geofence center`() = testScope.runTest {
- val location = mockLocation()
- setField("lastKnownLocation", location)
-
- invokeEnterPauseZone(homeGeofence)
-
- verify { dbHelper.saveLocation(
- latitude = homeGeofence.lat,
- longitude = homeGeofence.lon,
- accuracy = homeGeofence.radius,
- altitude = null,
- speed = null,
- bearing = null,
- battery = 80,
- battery_status = 2,
- timestamp = any(),
- endpoint = "https://example.com"
- ) }
- }
-
- @Test
- fun `enterPauseZone anchor queues sync after DB save`() = testScope.runTest {
+ fun `enterPauseZone does not save anchor on entry`() = testScope.runTest {
val location = mockLocation()
setField("lastKnownLocation", location)
- every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 42L
invokeEnterPauseZone(homeGeofence)
- coVerify { syncManager.queueAndSend(42L, any()) }
+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
}
@Test
@@ -856,17 +826,13 @@ class LocationForegroundServiceTest {
}
@Test
- fun `zone-to-zone transition skips anchor for second zone`() = testScope.runTest {
+ fun `enterPauseZone never saves anchor on zone entry`() = testScope.runTest {
val location = mockLocation()
setField("lastKnownLocation", location)
invokeEnterPauseZone(homeGeofence)
-
- clearMocks(dbHelper, answers = false)
-
invokeEnterPauseZone(officeGeofence)
- // No anchor saved when switching directly between zones (no trip in between)
verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
}
@@ -875,15 +841,15 @@ class LocationForegroundServiceTest {
// =========================================================================
@Test
- fun `recheckZone enters zone when not currently in zone`() {
+ fun `recheckZone starts entry delay when not currently in zone`() {
setField("insidePauseZone", false)
val location = mockLocation()
every { geofenceHelper.getPauseZone(location) } returns parkGeofence
invokeRecheckZoneWithLocation(location)
- assertTrue(getField("insidePauseZone"))
- assertEquals("Park", getField<String?>("currentZoneName"))
+ assertFalse(getField("insidePauseZone"))
+ assertEquals(parkGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@Test
@@ -900,7 +866,7 @@ class LocationForegroundServiceTest {
}
@Test
- fun `recheckZone changes zone when moving between zones`() {
+ fun `recheckZone starts entry delay when moving between zones`() {
setField("insidePauseZone", true)
setField("currentZoneName", "Home")
setField("currentZoneGeofence", homeGeofence)
@@ -909,12 +875,14 @@ class LocationForegroundServiceTest {
invokeRecheckZoneWithLocation(location)
+ // Still in Home until delay fires
assertTrue(getField("insidePauseZone"))
- assertEquals("Office", getField<String?>("currentZoneName"))
+ assertEquals("Home", getField<String?>("currentZoneName"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@Test
- fun `recheckZone zone-to-zone transition skips anchor for new zone`() = testScope.runTest {
+ fun `recheckZone zone-to-zone transition starts delay for new zone`() = testScope.runTest {
setField("insidePauseZone", true)
setField("currentZoneName", "Home")
setField("currentZoneGeofence", homeGeofence)
@@ -925,10 +893,10 @@ class LocationForegroundServiceTest {
invokeRecheckZoneWithLocation(location)
- // No anchor saved when switching directly between zones (no trip in between)
verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
- // State should still update
- assertEquals("Office", getField<String?>("currentZoneName"))
+ // Still in Home - delay pending for Office
+ assertEquals("Home", getField<String?>("currentZoneName"))
+ assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
}
@Test
@@ -973,6 +941,120 @@ class LocationForegroundServiceTest {
) }
}
+ // =========================================================================
+ // startEntryDelay / cancelEntryDelay
+ // =========================================================================
+
+ @Test
+ fun `startEntryDelay sets pendingPauseZone without entering zone`() {
+ invokeStartEntryDelay(homeGeofence)
+
+ assertFalse(getField("insidePauseZone"))
+ assertEquals(homeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNotNull(getField<Job?>("entryDelayJob"))
+ }
+
+ @Test
+ fun `startEntryDelay enters zone after delay completes`() = testScope.runTest {
+ invokeStartEntryDelay(homeGeofence)
+
+ assertFalse(getField("insidePauseZone"))
+
+ advanceTimeBy((5000L * 3.5 + 1).toLong())
+
+ assertTrue(getField("insidePauseZone"))
+ assertEquals("Home", getField<String?>("currentZoneName"))
+ assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ verify { LocationServiceModule.sendPauseZoneEvent(true, "Home") }
+ }
+
+ @Test
+ fun `startEntryDelay does not enter zone if pendingPauseZone cleared before timer fires`() = testScope.runTest {
+ invokeStartEntryDelay(homeGeofence)
+ setField("pendingPauseZone", null)
+
+ advanceTimeBy((5000L * 3.5 + 1).toLong())
+
+ assertFalse(getField("insidePauseZone"))
+ verify(exactly = 0) { LocationServiceModule.sendPauseZoneEvent(true, any()) }
+ }
+
+ @Test
+ fun `startEntryDelay cancels previous delay when called again`() {
+ invokeStartEntryDelay(homeGeofence)
+ val firstJob: Job? = getField("entryDelayJob")
+
+ invokeStartEntryDelay(officeGeofence)
+
+ assertTrue(firstJob?.isCancelled == true)
+ assertEquals(officeGeofence, getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ }
+
+ @Test
+ fun `cancelEntryDelay clears pendingPauseZone and job`() {
+ invokeStartEntryDelay(homeGeofence)
+
+ invokeCancelEntryDelay()
+
+ assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ assertNull(getField<Job?>("entryDelayJob"))
+ }
+
+ @Test
+ fun `cancelEntryDelay updates notification`() {
+ invokeStartEntryDelay(homeGeofence)
+ val loc = mockLocation(lat = 52.0, lon = 13.0)
+ setField("lastKnownLocation", loc)
+
+ invokeCancelEntryDelay()
+
+ verify { notificationHelper.update(
+ lat = 52.0,
+ lon = 13.0,
+ isPaused = false,
+ zoneName = null,
+ queuedCount = any(),
+ lastSyncTime = any(),
+ activeProfileName = any(),
+ forceUpdate = true
+ ) }
+ }
+
+ @Test
+ fun `handleLocationUpdate cancels delay when leaving zone mid-delay`() = testScope.runTest {
+ setField("pendingPauseZone", homeGeofence)
+ val mockJob = mockk<Job>(relaxed = true)
+ setField("entryDelayJob", mockJob)
+ every { geofenceHelper.getPauseZone(any()) } returns null
+ val location = mockLocation()
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+
+ invokeHandleLocationUpdate(location)
+
+ verify { mockJob.cancel() }
+ assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ }
+
+ @Test
+ fun `handleLocationUpdate bypasses distance filter during entry delay`() = testScope.runTest {
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 5000L,
+ minUpdateDistance = 50f,
+ filterInaccurateLocations = false
+ ))
+ val prev = mockLocation(distanceTo = 10f)
+ setField("lastKnownLocation", prev)
+ setField("pendingPauseZone", homeGeofence)
+ every { geofenceHelper.getPauseZone(any()) } returns homeGeofence
+ val location = mockLocation(distanceTo = 10f)
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+
+ invokeHandleLocationUpdate(location)
+
+ verify { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ }
+
// =========================================================================
// applyProfileConfig - dynamic config switching
// =========================================================================
@@ -1053,6 +1135,18 @@ class LocationForegroundServiceTest {
verify { notificationHelper.update(any(), any(), any(), any(), any(), any(), any(), forceUpdate = true) }
}
+ @Test
+ fun `applyProfileConfig cancels pending entry delay`() {
+ val mockJob = mockk<Job>(relaxed = true)
+ setField("entryDelayJob", mockJob)
+ setField("pendingPauseZone", homeGeofence)
+
+ invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)
+
+ verify { mockJob.cancel() }
+ assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ }
+
@Test
fun `applyProfileConfig cancels pending locationRestartJob`() {
val mockJob = mockk<Job>(relaxed = true)
@@ -1102,6 +1196,18 @@ class LocationForegroundServiceTest {
assertNull(getField<CoroutineScope?>("serviceScope"))
}
+ @Test
+ fun `onDestroy cancels entry delay job`() {
+ val mockJob = mockk<Job>(relaxed = true)
+ setField("entryDelayJob", mockJob)
+ setField("pendingPauseZone", homeGeofence)
+
+ invokeOnDestroy()
+
+ verify { mockJob.cancel() }
+ assertNull(getField<GeofenceHelper.CachedGeofence?>("pendingPauseZone"))
+ }
+
@Test
fun `onDestroy handles null location callback gracefully`() {
setField("locationUpdateCallback", null)
@@ -1287,6 +1393,26 @@ class LocationForegroundServiceTest {
assertNull("Should not start timer when sensor unavailable", stationaryJob)
}
+ @Test
+ fun `evaluateStationaryState skips when entry delay is pending`() = 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("pendingPauseZone", homeGeofence)
+
+ val location = mockLocation(speed = 0.1f)
+ invokeEvaluateStationaryState(location)
+
+ val stationaryJob: Job? = getField("stationaryJob")
+ assertNull("Should not start stationary timer during entry delay", stationaryJob)
+ }
+
@Test
fun `evaluateStationaryState starts timer when inside pause zone`() = testScope.runTest {
setField("config", ServiceConfig(
@@ -1438,6 +1564,20 @@ class LocationForegroundServiceTest {
// Reflection helpers
// =========================================================================
+ private fun invokeStartEntryDelay(geofence: GeofenceHelper.CachedGeofence) {
+ val method = LocationForegroundService::class.java.getDeclaredMethod(
+ "startEntryDelay", GeofenceHelper.CachedGeofence::class.java
+ )
+ method.isAccessible = true
+ method.invoke(service, geofence)
+ }
+
+ private fun invokeCancelEntryDelay() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("cancelEntryDelay")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
private fun invokeEvaluateStationaryState(location: Location) {
val method = LocationForegroundService::class.java.getDeclaredMethod(
"evaluateStationaryState", Location::class.java