Skip to content

Colota - Android GPS Location tracker

fix(geofence): resume tracking after leaving a geofence zone

Max Dietrich781bc51c1a16
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index dea7ad55..d1dc0bc8 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -81,6 +81,7 @@ See the [Deep Link Setup](deep-link-setup.md#geofences) guide for the full paylo
- If you leave before the entry delay completes, the delay is cancelled and tracking continues uninterrupted
- Stationary detection is suspended inside zones so GPS is never stopped by the stationary timer while zone exit needs to be detected
- When exiting the zone, tracking automatically resumes
+- If GPS goes quiet while paused (for example, indoors for a long stretch), Colota periodically requests a fresh position to check whether you have left
- Zone checks happen every location update with minimal overhead
- You can create unlimited geofence zones
diff --git a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
index 89ae6b8d..d5d9c072 100644
--- a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
+++ b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
@@ -11,8 +11,14 @@ import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
+import android.os.CancellationSignal
+import android.os.Handler
import android.os.Looper
+import androidx.core.location.LocationManagerCompat
+import androidx.core.util.Consumer
import com.Colota.util.AppLogger
+import java.util.concurrent.Executor
+import java.util.concurrent.atomic.AtomicBoolean
/**
* LocationManager-based GPS provider for FOSS flavor (no Google Play Services).
@@ -79,4 +85,38 @@ class NativeLocationProvider(context: Context) : LocationProvider {
onFailure(e)
}
}
+
+ override fun getCurrentLocation(timeoutMs: Long, onResult: (Location?) -> Unit) {
+ // Guard delivery so the timeout and the consumer can't both fire onResult.
+ val delivered = AtomicBoolean(false)
+ fun deliver(location: Location?) {
+ if (delivered.compareAndSet(false, true)) onResult(location)
+ }
+
+ val handler = Handler(Looper.getMainLooper())
+ val cancellationSignal = CancellationSignal()
+ val timeoutRunnable = Runnable {
+ cancellationSignal.cancel()
+ deliver(null)
+ }
+
+ try {
+ LocationManagerCompat.getCurrentLocation(
+ locationManager,
+ LocationManager.GPS_PROVIDER,
+ cancellationSignal,
+ Executor { handler.post(it) },
+ Consumer { location ->
+ handler.removeCallbacks(timeoutRunnable)
+ deliver(location)
+ }
+ )
+ handler.postDelayed(timeoutRunnable, timeoutMs)
+ AppLogger.d(TAG, "Requested fresh GPS_PROVIDER fix (timeout=${timeoutMs}ms)")
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Fresh GPS_PROVIDER fix failed: ${e.message}")
+ handler.removeCallbacks(timeoutRunnable)
+ deliver(null)
+ }
+ }
}
diff --git a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt
index 1748008c..a4be31c9 100644
--- a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt
+++ b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt
@@ -69,4 +69,24 @@ class GmsLocationProvider(context: Context) : LocationProvider {
onFailure(e)
}
}
+
+ override fun getCurrentLocation(timeoutMs: Long, onResult: (Location?) -> Unit) {
+ // setMaxUpdateAgeMillis(0) forbids the cached fix, forcing a real GNSS acquisition.
+ val request = CurrentLocationRequest.Builder()
+ .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
+ .setMaxUpdateAgeMillis(0)
+ .setDurationMillis(timeoutMs)
+ .build()
+ try {
+ fusedClient.getCurrentLocation(request, null)
+ .addOnSuccessListener { onResult(it) }
+ .addOnFailureListener { onResult(null) }
+ AppLogger.d(TAG, "Requested fresh fused fix (maxAge=0, timeout=${timeoutMs}ms)")
+ } catch (e: Exception) {
+ // Broad: a synchronous throw before the Task is wired must still deliver, or the caller's
+ // in-flight guard latches and every future probe is throttled. Mirrors the FOSS provider.
+ AppLogger.w(TAG, "Fresh fused fix failed: ${e.message}")
+ onResult(null)
+ }
+ }
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index 20f9abeb..c71dab60 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -301,6 +301,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
val serviceConfig = ServiceConfig.fromReadableMap(config, dbHelper)
val serviceIntent = Intent(reactApplicationContext, LocationForegroundService::class.java)
serviceConfig.toIntent(serviceIntent)
+ serviceIntent.putExtra(LocationForegroundService.EXTRA_USER_INITIATED, true)
try {
reactApplicationContext.startForegroundService(serviceIntent)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/location/LocationProvider.kt b/apps/mobile/android/app/src/main/java/com/colota/location/LocationProvider.kt
index 1ffe64ff..3617e15e 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/location/LocationProvider.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/location/LocationProvider.kt
@@ -44,6 +44,17 @@ interface LocationProvider {
onSuccess: (Location?) -> Unit,
onFailure: (Exception) -> Unit
)
+
+ /**
+ * Actively acquire one fresh fix, forbidding cached locations.
+ *
+ * @param timeoutMs Max time to wait for the fix.
+ * @param onResult Called once with the fix, or null on timeout/failure.
+ */
+ fun getCurrentLocation(
+ timeoutMs: Long,
+ onResult: (Location?) -> Unit
+ )
}
/**
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 66f8f6bc..c683a46e 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
@@ -68,6 +68,11 @@ class LocationForegroundService : Service() {
@Volatile private var motionDetector: MotionStateDetector? = null
@Volatile private var lastKnownLocation: Location? = null
+ // Rate-limit the fresh-fix probe so repeated rechecks/resumes don't spin up GNSS. Main-thread only.
+ @Volatile private var lastFreshProbeAtMs: Long? = null
+ @Volatile private var freshProbeInFlight = false
+ @Volatile private var pauseWatchdogJob: Job? = null
+
/** Re-entry guard for stopForegroundServiceWithReason: the battery monitor can fire again
* before onDestroy unregisters it. */
@Volatile private var isStopping = false
@@ -141,6 +146,18 @@ class LocationForegroundService : Service() {
/** Gaps above this bypass the filter so post-resume fixes aren't dropped. */
private const val POSITION_JUMP_FILTER_WINDOW_MS = 300_000L
+ /** Timeout for the active fresh-fix probe (ms). */
+ private const val FRESH_FIX_TIMEOUT_MS = 30_000L
+ /** Minimum spacing between fresh-fix probes; throttled callers get the last-known fix. */
+ private const val FRESH_PROBE_MIN_INTERVAL_MS = 60_000L
+ /** A fix older than this by the monotonic clock isn't trusted to hold a pause - usually a stale/replayed fix. */
+ private const val STALE_FIX_THRESHOLD_MS = 5 * 60_000L
+ /** Paused-watchdog tick cadence and the floor for its stall threshold (#444). */
+ private const val PAUSE_WATCHDOG_INTERVAL_MS = 10 * 60_000L
+ /** The stream counts as stalled after this many tracking intervals without a fix (floored at
+ * [PAUSE_WATCHDOG_INTERVAL_MS]), so a long interval isn't probed more often than configured. */
+ private const val PAUSE_WATCHDOG_STALL_INTERVALS = 2
+
const val ACTION_MANUAL_FLUSH = "com.Colota.ACTION_MANUAL_FLUSH"
const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"
const val ACTION_REFRESH_NOTIFICATION = "com.Colota.REFRESH_NOTIFICATION"
@@ -148,6 +165,8 @@ class LocationForegroundService : Service() {
/** Internal stop request from triggers (broadcast receiver, shortcut activity). */
const val ACTION_STOP_REQUEST = "com.Colota.ACTION_STOP_REQUEST"
const val EXTRA_STOP_REASON = "stop_reason"
+ /** Set by the bridge on an explicit user start so the restored-pause path can force-exit on no fix. */
+ const val EXTRA_USER_INITIATED = "user_initiated"
/** Debug-only: directly inject a MotionState transition. `--es state STATIONARY|MOVING`. */
const val ACTION_DEBUG_FORCE_MOTION = "com.Colota.DEBUG_FORCE_MOTION"
@@ -319,7 +338,7 @@ class LocationForegroundService : Service() {
ACTION_STOP_REQUEST -> stopForegroundServiceWithReason(
intent.getStringExtra(EXTRA_STOP_REASON) ?: "Stopped"
)
- else -> handleStart()
+ else -> handleStart(intent?.getBooleanExtra(EXTRA_USER_INITIATED, false) ?: false)
}
return START_STICKY
@@ -355,14 +374,14 @@ class LocationForegroundService : Service() {
}
}
- private fun handleStart() {
+ private fun handleStart(userInitiated: Boolean) {
locationRestartJob?.cancel()
locationRestartJob = serviceScope?.launch {
withContext(Dispatchers.Main) {
stopLocationUpdates()
syncManager.stopPeriodicSync()
- setupLocationUpdates()
+ setupLocationUpdates(userInitiated)
syncManager.startPeriodicSync()
// Start after setup so profile evaluations don't race
@@ -413,7 +432,7 @@ class LocationForegroundService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
- private fun setupLocationUpdates() {
+ private fun setupLocationUpdates(userInitiatedStart: Boolean = false) {
if (isWifiPaused || isMotionlessPaused) return // GPS intentionally stopped by a zone pause hold
val callback = object : LocationUpdateCallback {
@@ -446,21 +465,39 @@ class LocationForegroundService : Service() {
)
lastRequestedBypassOsFilter = bypassOsFilter
- locationProvider.getLastLocation(
- onSuccess = { location ->
- location?.let {
- lastKnownLocation = it
- geofenceHelper.getPauseZone(it)?.let { zone ->
- enterPauseZone(zone)
- } ?: run {
- updateNotification(it.latitude, it.longitude, forceUpdate = true)
- }
+ // A restored pause must be re-checked against a fresh fix: a cached fix can only
+ // re-enter, never exit, so a departed user would stay latched. On no usable fix an
+ // explicit user start forces exit (stop/start "kick it loose"); an OS auto-restart stays
+ // put so a restart while genuinely at home doesn't record a false point. Cold start keeps last-known.
+ val restoredPause = insidePauseZone
+ if (restoredPause) {
+ requestFreshOrLastLocation { location, _ ->
+ if (location != null) {
+ lastKnownLocation = location
+ recheckZoneWithLocation(location)
+ } else if (userInitiatedStart) {
+ AppLogger.d(TAG, "User-initiated start with no usable fix - forcing exit from zone")
+ exitPauseZone()
}
- },
- onFailure = { /* initial location unavailable, updates will arrive */ }
- )
+ }
+ } else {
+ locationProvider.getLastLocation(
+ onSuccess = { location ->
+ location?.let {
+ lastKnownLocation = it
+ geofenceHelper.getPauseZone(it)?.let { zone ->
+ enterPauseZone(zone)
+ } ?: run {
+ updateNotification(it.latitude, it.longitude, forceUpdate = true)
+ }
+ }
+ },
+ onFailure = { /* initial location unavailable, updates will arrive */ }
+ )
+ }
startTrackingHeartbeatLogger()
+ startPauseWatchdog()
} catch (e: SecurityException) {
AppLogger.e(TAG, "Location permission missing", e)
stopForegroundServiceWithReason("Location permission missing")
@@ -472,6 +509,7 @@ class LocationForegroundService : Service() {
private fun stopLocationUpdates() {
cancelTrackingHeartbeatLogger()
+ stopPauseWatchdog()
locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }
locationUpdateCallback = null
}
@@ -524,7 +562,117 @@ class LocationForegroundService : Service() {
trackingHeartbeatJob = null
}
+ /**
+ * Fresh fix (no cached locations), falling back to last-known on timeout. Rate-limited to one
+ * probe in flight and one per [FRESH_PROBE_MIN_INTERVAL_MS]; throttled callers get last-known.
+ * The callback's second arg is true only when a fresh probe actually ran (false when throttled),
+ * so a caller won't force-exit on a throttled stale fallback. Main-thread only, so it's race-free.
+ */
+ private fun requestFreshOrLastLocation(onResult: (Location?, Boolean) -> Unit) {
+ val now = SystemClock.elapsedRealtime()
+ val last = lastFreshProbeAtMs
+ if (freshProbeInFlight || (last != null && now - last < FRESH_PROBE_MIN_INTERVAL_MS)) {
+ AppLogger.d(TAG, "Fresh-fix probe throttled (inFlight=$freshProbeInFlight) - using last-known")
+ deliverLastKnownIfFresh { onResult(it, false) }
+ return
+ }
+
+ freshProbeInFlight = true
+ lastFreshProbeAtMs = now
+ locationProvider.getCurrentLocation(FRESH_FIX_TIMEOUT_MS) { fresh ->
+ freshProbeInFlight = false
+ if (fresh != null && isFixFresh(fresh)) {
+ onResult(fresh, true)
+ } else {
+ // A non-null but stale probe (some chips replay a cached fix on a refreshed timestamp
+ // despite maxUpdateAge=0) must not re-confirm the pause - fall through to last-known.
+ deliverLastKnownIfFresh { onResult(it, true) }
+ }
+ }
+ }
+
+ /**
+ * Serves the last-known fix only if recent. A stale one is usually the in-zone fix that latched
+ * the pause, so it's reported as null - letting paused callers force-exit instead of re-latching.
+ */
+ private fun deliverLastKnownIfFresh(onResult: (Location?) -> Unit) {
+ locationProvider.getLastLocation(
+ onSuccess = { location ->
+ if (location != null && isFixFresh(location)) {
+ onResult(location)
+ } else {
+ if (location != null) AppLogger.d(TAG, "Last-known fix is stale - treating as no fix")
+ onResult(null)
+ }
+ },
+ onFailure = { onResult(null) }
+ )
+ }
+
+ /**
+ * Freshness by the monotonic clock (elapsedRealtimeNanos), which a chip cannot refresh when it
+ * replays a cached fix - unlike wall-clock time. Used to reject a stale fix on any recovery path.
+ */
+ private fun isFixFresh(location: Location): Boolean {
+ val ageMs = (SystemClock.elapsedRealtimeNanos() - location.elapsedRealtimeNanos) / 1_000_000L
+ return ageMs < STALE_FIX_THRESHOLD_MS
+ }
+
+ /**
+ * Periodically re-evaluates the pause zone against a fresh fix so a departure resumes without
+ * the user opening the app. Tied to the GPS-stream lifecycle like the heartbeat logger; each
+ * tick self-gates (see [runPauseWatchdogTick]).
+ */
+ private fun startPauseWatchdog() {
+ pauseWatchdogJob?.cancel()
+ val scope = serviceScope ?: return
+ pauseWatchdogJob = scope.launch {
+ while (isActive) {
+ delay(PAUSE_WATCHDOG_INTERVAL_MS)
+ withContext(Dispatchers.Main) { runPauseWatchdogTick() }
+ }
+ }
+ }
+
+ private fun stopPauseWatchdog() {
+ pauseWatchdogJob?.cancel()
+ pauseWatchdogJob = null
+ }
+
+ private fun runPauseWatchdogTick() {
+ // Wifi/motionless holds stop GPS and own their own resume - don't probe over them.
+ if (!insidePauseZone || isWifiPaused || isMotionlessPaused) return
+ // Only probe once the stream has been quiet longer than the interval would explain (a real stall).
+ val sinceLastFix = SystemClock.elapsedRealtime() - lastFixAtMs
+ val quietThresholdMs = maxOf(PAUSE_WATCHDOG_INTERVAL_MS, config.interval * PAUSE_WATCHDOG_STALL_INTERVALS)
+ if (sinceLastFix < quietThresholdMs) return
+ AppLogger.i(TAG, "Pause watchdog: stream quiet ${sinceLastFix / 1000}s - re-evaluating zone")
+ requestFreshOrLastLocation { location, _ ->
+ // Act only on a usable fix - a stale/absent one leaves the pause untouched (no home false-exits).
+ location?.let {
+ lastKnownLocation = it
+ recheckZoneWithLocation(it)
+ }
+ }
+ }
+
private fun handleZoneRecheckAction() {
+ // A cached fix while paused is usually the stale home fix - force a fresh one so a departure exits.
+ if (insidePauseZone) {
+ requestFreshOrLastLocation { location, probed ->
+ if (location != null) {
+ lastKnownLocation = location
+ recheckZoneWithLocation(location)
+ } else if (probed) {
+ // Only a genuine probe that found nothing exits. A throttled stale fallback must
+ // not fabricate a departure while genuinely at home (eg an edit right after a watchdog probe).
+ AppLogger.d(TAG, "No location for recheck, forcing exit from zone")
+ exitPauseZone()
+ }
+ }
+ return
+ }
+
val cachedLoc = lastKnownLocation
val now = System.currentTimeMillis()
@@ -536,18 +684,10 @@ class LocationForegroundService : Service() {
if (location != null) {
lastKnownLocation = location
recheckZoneWithLocation(location)
- } else {
- if (insidePauseZone) {
- AppLogger.d(TAG, "No location for recheck, forcing exit from zone")
- exitPauseZone()
- }
}
},
onFailure = { e ->
AppLogger.e(TAG, "Recheck error", e)
- if (insidePauseZone) {
- exitPauseZone()
- }
}
)
}
@@ -665,6 +805,8 @@ class LocationForegroundService : Service() {
}
// Position-jump filter: chip-reported and implied speed are independent signals; large disagreement means the chip hallucinated position.
+ // Kept active while paused too: a real departure passes it anyway (implied speed agrees with
+ // chip, or is below the floor), but one hallucinated jump must not fake a departure.
if (prev != null && location.hasSpeed()) {
val dt = location.time - prev.time
if (dt in 1000..POSITION_JUMP_FILTER_WINDOW_MS) {
@@ -685,8 +827,9 @@ class LocationForegroundService : Service() {
// Software-side distance filter. Enforces config.minUpdateDistance for DB/sync
// regardless of the OS filter (which passes 0m to when a location-dependent
- // profile is enabled). Bypassed during entry delay so arrival points get logged.
- if (pendingPauseZone == null && config.minUpdateDistance > 0f && prev != null) {
+ // profile is enabled). Bypassed during entry delay so arrival points get logged, and while
+ // paused so a small step across the radius reaches the zone-exit check (the radius still gates it).
+ if (!insidePauseZone && 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")
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 e4755094..8391a609 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
@@ -79,6 +79,11 @@ class LocationForegroundServiceTest {
every { deviceInfoHelper.isBatteryCritical() } returns false
every { deviceInfoHelper.isLocationEnabled() } returns true
every { geofenceHelper.getPauseZone(any()) } returns null
+ // Default the fresh-fix probe to a timeout (null) so requestFreshOrLastLocation falls
+ // back to getLastLocation, preserving prior recheck-test behavior. Fresh-path tests override.
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(null)
+ }
mockkObject(PayloadBuilder)
every { PayloadBuilder.buildLocationPayload(any(), any(), any(), any(), any(), any(), any()) } returns JSONObject()
every { PayloadBuilder.parseFieldMap(any()) } returns null
@@ -186,6 +191,7 @@ class LocationForegroundServiceTest {
bearing: Float = 90f,
hasBearing: Boolean = true,
time: Long = System.currentTimeMillis(),
+ elapsedNanos: Long = 0L,
distanceTo: Float = 0f
): Location = mockk {
every { latitude } returns lat
@@ -198,6 +204,7 @@ class LocationForegroundServiceTest {
every { [email protected] } returns bearing
every { hasBearing() } returns hasBearing
every { [email protected] } returns time
+ every { elapsedRealtimeNanos } returns elapsedNanos
every { provider } returns "gps"
every { distanceTo(any()) } returns distanceTo
every { setSpeed(any()) } just Runs
@@ -778,6 +785,296 @@ class LocationForegroundServiceTest {
assertEquals(freshLocation, getField<Location?>("lastKnownLocation"))
}
+ // =========================================================================
+ // #444 - restored / paused zone recheck against a fresh fix
+ // =========================================================================
+
+ @Test
+ fun `recheck while paused forces a fresh fix and exits when it lands outside`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ val fresh = mockLocation(lat = 48.0, lon = 11.0)
+ every { geofenceHelper.getPauseZone(fresh) } returns null
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(fresh)
+ }
+
+ invokeHandleZoneRecheckAction()
+
+ verify { locationProvider.getCurrentLocation(any(), any()) }
+ assertFalse(getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `recheck while paused stays paused when the fresh fix is still inside`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ val fresh = mockLocation(lat = 52.50, lon = 13.40)
+ every { geofenceHelper.getPauseZone(fresh) } returns homeGeofence
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(fresh)
+ }
+
+ invokeHandleZoneRecheckAction()
+
+ assertTrue(getField("insidePauseZone"))
+ assertEquals("Home", getField<String?>("currentZoneName"))
+ }
+
+ @Test
+ fun `recheck while paused falls back to last-known when the fresh fix times out`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ val lastKnown = mockLocation(lat = 48.0, lon = 11.0)
+ every { geofenceHelper.getPauseZone(lastKnown) } returns null
+ // getCurrentLocation defaults to null (timeout) from setUp.
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(lastKnown)
+ }
+
+ invokeHandleZoneRecheckAction()
+
+ verify { locationProvider.getLastLocation(any(), any()) }
+ assertFalse(getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `paused recheck throttles a second fresh probe within the min interval`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ val fresh = mockLocation(lat = 52.50, lon = 13.40) // still inside -> stays paused
+ every { geofenceHelper.getPauseZone(fresh) } returns homeGeofence
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(fresh)
+ }
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(fresh)
+ }
+
+ invokeHandleZoneRecheckAction() // first: spins the fresh probe
+ invokeHandleZoneRecheckAction() // second: throttled -> serves last-known instead
+
+ verify(exactly = 1) { locationProvider.getCurrentLocation(any(), any()) }
+ verify { locationProvider.getLastLocation(any(), any()) }
+ }
+
+ @Test
+ fun `recheck while paused force-exits when the only available fix is a stale in-zone fix`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ // Probe times out (default getCurrentLocation stub -> null), and the last-known fix is the
+ // old in-zone home fix (stale by the monotonic clock). getPauseZone returns Home for it, so
+ // without the staleness guard it would re-confirm the pause - the guard must force exit instead.
+ val stale = mockLocation(lat = 52.50, lon = 13.40, elapsedNanos = -(10L * 60_000L) * 1_000_000L)
+ every { geofenceHelper.getPauseZone(stale) } returns homeGeofence
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(stale)
+ }
+
+ invokeHandleZoneRecheckAction()
+
+ assertFalse("a stale in-zone fix must not re-confirm the pause", getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `recheck while paused force-exits when the probe returns a stale replayed fix`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ // A chip replays the cached in-zone fix - non-null but old by the monotonic clock - and
+ // getPauseZone returns Home for it, so without the guard it would re-confirm the pause.
+ val staleProbe = mockLocation(lat = 52.50, lon = 13.40, elapsedNanos = -(6L * 60_000L) * 1_000_000L)
+ every { geofenceHelper.getPauseZone(staleProbe) } returns homeGeofence
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(staleProbe)
+ }
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(null)
+ }
+
+ invokeHandleZoneRecheckAction()
+
+ assertFalse("a stale replayed probe fix must not re-confirm the pause", getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `throttled paused recheck does not fabricate a departure on a stale last-known`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ // A fresh probe ran moments ago (SystemClock.elapsedRealtime()=0 in tests), so this recheck is
+ // throttled to the stale last-known home fix. It must STAY paused, not fabricate a departure.
+ setField("lastFreshProbeAtMs", 0L)
+ val staleHome = mockLocation(lat = 52.50, lon = 13.40, elapsedNanos = -(10L * 60_000L) * 1_000_000L)
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(staleHome)
+ }
+
+ invokeHandleZoneRecheckAction()
+
+ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }
+ assertTrue("a throttled recheck with a stale fix must not force a departure", getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `user-initiated start force-exits a restored pause when there is no usable fix`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ // Fresh probe times out (default stub -> null) and last-known is unavailable.
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(null)
+ }
+
+ invokeSetupLocationUpdates(userInitiated = true)
+
+ assertFalse("explicit stop/start must kick a stuck pause loose", getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `os auto-restart leaves a restored pause untouched when there is no usable fix`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ every { locationProvider.getLastLocation(any(), any()) } answers {
+ firstArg<(Location?) -> Unit>()(null)
+ }
+
+ invokeSetupLocationUpdates(userInitiated = false)
+
+ assertTrue("an OS restart at home with no fix must not record a false exit", getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `pause watchdog does not probe while the live stream is still delivering fixes`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", homeGeofence)
+ setField("lastFixAtMs", 0L) // SystemClock.elapsedRealtime()=0 in tests -> stream "just delivered"
+
+ invokeRunPauseWatchdogTick()
+
+ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }
+ }
+
+ @Test
+ fun `pause watchdog probes and exits when the stream is quiet and the fresh fix is outside`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ setField("lastFixAtMs", -700_000L) // sinceLastFix > 10min interval -> stream quiet
+ val fresh = mockLocation(lat = 48.0, lon = 11.0)
+ every { geofenceHelper.getPauseZone(fresh) } returns null
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(fresh)
+ }
+
+ invokeRunPauseWatchdogTick()
+
+ verify { locationProvider.getCurrentLocation(any(), any()) }
+ assertFalse(getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `pause watchdog stays paused when the quiet-stream probe is still inside`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+ setField("lastFixAtMs", -700_000L)
+ val fresh = mockLocation(lat = 52.50, lon = 13.40)
+ every { geofenceHelper.getPauseZone(fresh) } returns homeGeofence
+ every { locationProvider.getCurrentLocation(any(), any()) } answers {
+ secondArg<(Location?) -> Unit>()(fresh)
+ }
+
+ invokeRunPauseWatchdogTick()
+
+ assertTrue(getField("insidePauseZone"))
+ }
+
+ @Test
+ fun `pause watchdog skips probing while a motionless hold has GPS stopped`() {
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", homeGeofence)
+ setField("isMotionlessPaused", true)
+ setField("lastFixAtMs", -700_000L)
+
+ invokeRunPauseWatchdogTick()
+
+ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }
+ }
+
+ @Test
+ fun `pause watchdog stall threshold scales with the configured interval`() {
+ // 30-min interval -> stall threshold max(10min, 60min) = 60min, so an 11-min gap that would
+ // trip the fixed 10-min floor must NOT probe; the watchdog respects the user's interval.
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 30 * 60_000L,
+ accuracyThreshold = 50f,
+ filterInaccurateLocations = true,
+ syncIntervalSeconds = 0
+ ))
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", homeGeofence)
+ setField("lastFixAtMs", -700_000L) // ~11.6 min: past the 10-min floor, well under 60min
+
+ invokeRunPauseWatchdogTick()
+
+ verify(exactly = 0) { locationProvider.getCurrentLocation(any(), any()) }
+ }
+
+ @Test
+ fun `handleLocationUpdate while paused rejects a hallucinated outlier instead of fabricating an exit`() = testScope.runTest {
+ // A teleport-signature fix (huge implied speed, ~0 chip speed) lands outside the radius but
+ // must not fake a departure - the jump filter stays active while paused.
+ val prev = mockLocation(lat = 52.50, lon = 13.40, time = 1_000_000L, distanceTo = 2000f)
+ setField("lastKnownLocation", prev)
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+
+ val outlier = mockLocation(lat = 48.0, lon = 11.0, speed = 1f, hasSpeed = true, time = 1_002_000L)
+ every { geofenceHelper.getPauseZone(outlier) } returns null
+
+ invokeHandleLocationUpdate(outlier)
+
+ assertTrue("paused zone must not exit on a single hallucinated outlier", getField("insidePauseZone"))
+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `handleLocationUpdate while paused exits on a genuine departure the min-distance filter would drop`() = testScope.runTest {
+ // While paused the min-distance filter is bypassed so a small step across the radius still
+ // reaches the zone-exit check; getPauseZone enforces the actual radius (#444).
+ setField("config", ServiceConfig(
+ endpoint = "https://example.com",
+ interval = 5000L,
+ minUpdateDistance = 50f,
+ accuracyThreshold = 50f,
+ filterInaccurateLocations = true,
+ syncIntervalSeconds = 0
+ ))
+ val prev = mockLocation(lat = 52.50, lon = 13.40, time = 1_000_000L, distanceTo = 30f)
+ setField("lastKnownLocation", prev)
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", homeGeofence)
+
+ // 30m step (< 50m min-distance) just outside the radius, no chip speed -> jump filter N/A.
+ val departing = mockLocation(lat = 52.49, lon = 13.39, hasSpeed = false, time = 1_020_000L)
+ every { geofenceHelper.getPauseZone(departing) } returns null
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+
+ invokeHandleLocationUpdate(departing)
+
+ assertFalse("a sub-min-distance departure must still exit while paused", getField("insidePauseZone"))
+ }
+
// =========================================================================
// enterPauseZone / exitPauseZone state transitions
// =========================================================================
@@ -2017,13 +2314,20 @@ class LocationForegroundServiceTest {
method.invoke(service)
}
- private fun invokeSetupLocationUpdates() {
+ private fun invokeRunPauseWatchdogTick() {
val method = LocationForegroundService::class.java
- .getDeclaredMethod("setupLocationUpdates")
+ .getDeclaredMethod("runPauseWatchdogTick")
method.isAccessible = true
method.invoke(service)
}
+ private fun invokeSetupLocationUpdates(userInitiated: Boolean = false) {
+ val method = LocationForegroundService::class.java
+ .getDeclaredMethod("setupLocationUpdates", Boolean::class.javaPrimitiveType)
+ method.isAccessible = true
+ method.invoke(service, userInitiated)
+ }
+
private fun invokeHandleRecheckProfiles() {
val method = LocationForegroundService::class.java
.getDeclaredMethod("handleRecheckProfiles")