Modern Apps git

← Modern-Apps.git

findfamily: keep the sender producing fresh fixes while "still" (#895)

Commit
34d3e1c9d3f08759314183bbb5781d680dfb20e2
Author
Vayun Mathur <[email protected]>
When
2026-11-12 04:39 UTC (24 days ago)
Parents
f32d62b
Symptom (GitHub #895): family members' pins stopped moving. One pin
stayed at work for 8 h while she was at home; leaving home was not
detected although small jitter at home was; later updates came
irregularly (~every 3 min). The relay server was healthy (0 errors),
and the cards said "updated just now" because the sender kept
re-publishing an old fix.

Root cause, on the sending phone:
- Location updates only ran while the phone counted as "moving", and
  "moving" was decided by acceleration alone: 60 s of linear
  acceleration under 0.5 m/s^2 meant "still". Steady car, bus or tram
  travel easily stays under that.
- Once "still", the only way back was the one-shot significant-motion
  sensor. On many phones it is step-driven and does not fire in
  vehicles.
- Nothing produced a fix while "still": setupLocationUpdates() and
  startGps() return early, and the heartbeat only re-sends
  lastKnownLocation, however old.
- Fixes coarser than 100 m (NoShowPolicy.NO_SHOW_MAX_ACCURACY_METERS)
  are dropped at intake, so in a city with coarse network fixes even
  the fixes that did arrive could not reveal a departure.
- Side bug: on a fresh service start with a significant-motion sensor,
  the accelerometer was never registered, so the phone never went
  still (kept active updates) until the trigger fired once.

Changes (sender only):
- domain/MovementDetector: pure moving/still state machine. Any of
  acceleration > 0.5 m/s^2 (unchanged), a provider speed clearly
  above walking (> 2 m/s after subtracting the speed accuracy), or a
  displacement from the last reference point of > 75 m AND more than
  2x both fixes' error radii (non-overlapping ~95 % circles) counts
  as moving. "Still" now needs BOTH 60 s without acceleration AND
  4 min without fix-based movement. Fixes of any accuracy feed it,
  so a 600 m network fix 3 km from home wakes it. Old (> 2 min)
  replayed fixes are ignored; a sharper consistent fix refines the
  reference point so a slow departure still accumulates.
- domain/ForcedFixPolicy: when the held fix is older than 10 min
  (5 min charging, 15 min power-save), request a one-off current
  location, at most once per interval. Network first (20 s timeout);
  GPS (30 s timeout) only when network gives nothing fine enough to
  display, never in power-save unless there is no network provider.
- platform/LocationKeepAlive: one fix intake (onLocationFix) used by
  every listener: the movement detector sees each fix first, then
  recordFix applies the unchanged 100 m display gate. An always-on
  low-power NETWORK request (3 min, 5 min in power-save, 75 m
  displacement filter) plus a PASSIVE request stay registered for
  the service's life, so leaving a place by any means produces a fix.
  keepAliveTick() runs on each 30 s heartbeat (unlocked and
  pre-unlock loops): stillness re-check, request upkeep, forced fix.
  The forced fix goes through LocationManager.getCurrentLocation
  behind a CurrentLocationSource seam for tests.
- LocationTrackingService: isMoving now comes from the detector;
  the significant-motion trigger and the accelerometer feed it as
  extra wake-ups instead of being the only ones. Accelerometer
  registration is tracked so it is re-armed whenever the phone
  becomes moving (including via a fix) and dropped when it goes
  still, as before. Low-power/passive requests are removed in
  onDestroy. No Play services: platform LocationManager providers
  only (NETWORK, GPS, PASSIVE), same as before.
- LocationTrackingDirectBoot: the pre-unlock path uses the same
  startMovingNow()/keepAliveTick(); two pre-existing over-long log
  lines in that file are wrapped (detekt MaxLineLength).
- findfamily/AGENTS.md: key-files entries for the three new files.

Battery tradeoffs:
- Low-power NETWORK request: cell/Wi-Fi only, no GPS radio, every
  3 min (5 min power-save), delivered only after 75 m of movement.
  PASSIVE costs nothing (other apps' fixes).
- Forced fix while still: one network fix per 10 min on battery. GPS
  runs for at most 30 s per interval, only when network is coarse or
  absent, and not in power-save (so a phone indoors in a city
  costs at most ~5 % GPS duty). Charging tightens to 5 min.
- Going still now takes up to 4 min after the last fix-based
  movement (was 60 s of quiet acceleration), so every stop costs a
  few extra minutes of active updates; a spurious wake from network
  jitter is limited by the 2x error-radius rule.
- Doze/FGS: no new wakelocks or alarms. The service is already a
  location-type foreground service; location deliveries wake it, and
  the forced-fix check rides the existing heartbeat tick, so in deep
  Doze it runs whenever the process next wakes.
- Power-save behaviour is kept: active-mode intervals (network 30 s,
  GPS 180 s) are unchanged and power-save never adds forced GPS.

Alternatives rejected:
- Changing how the receiver stamps or shows times (the heartbeat's
  `now`, LocationValue, UserCard): deliberately left alone per the
  owner. The timestamps are not the cause; the sender stopped
  producing fixes, and the locations are supposed to update.
- Lowering the acceleration threshold: still fails for smooth
  vehicles and would keep active updates on for desk jostles.
- Running GPS continuously or on a short timer: drains the battery,
  which reporters explicitly praised the app for not doing.
- Relaxing the 100 m accuracy gate: NoShowPolicy uses it so coarse
  fixes never decide geofence/no-show state or move pins around a
  city; instead coarse fixes now only wake movement detection.
- Play services fused/activity recognition: not available by design.

User-visible effect: a sharing phone that leaves a place by car, bus,
tram or on foot is picked up within minutes, and a phone that stays
put still refreshes its fix at least every 10 min (5 min while
charging), so pins no longer freeze for hours.

Verification: unit tests for the state machine and forced-fix policy
(domain/MovementDetectorTest: vehicle with low acceleration but
displacement stays moving, speed wakes a still phone, walking pace and
uncertain speed don't, coarse far fix wakes, home jitter doesn't,
stationary goes still only when both signals are quiet, stale-fix and
GPS-fallback rules) and Robolectric service tests
(platform/LocationKeepAliveTest: low-power and passive requests stay
on while still, power-save interval, coarse fix wakes movement but is
not held, vehicle stays moving then goes still, stale held fix forces
one fix per interval and tighter while charging, GPS fallback only
when network is too coarse). Ran :findfamily:compileDevKotlin,
:findfamily:testDevUnitTest, :findfamily:lint and :findfamily:detekt
in the toolchain container.

Diff

findfamily/AGENTS.md
diff --git a/findfamily/AGENTS.md b/findfamily/AGENTS.mdindex 0d663e1b7f..76fdc0bd82 100644--- a/findfamily/AGENTS.md+++ b/findfamily/AGENTS.md@@ -43,9 +43,11 @@ WebSocket relay host: `wss://api.maproj.org/api/ws` (Cloudflare FIRST_PARTY pins - com/vayunmathur/findfamily/data/Coord.kt - com/vayunmathur/findfamily/data/LocationValue.kt - com/vayunmathur/findfamily/data/DirectBootStore.kt-### domain/ — pairing auth + no-show policy (pure logic)+### domain/ — pairing auth, no-show policy, sender movement policy (pure logic) - com/vayunmathur/findfamily/domain/PairAuth.kt - com/vayunmathur/findfamily/domain/NoShowPolicy.kt+- com/vayunmathur/findfamily/domain/MovementDetector.kt — sender moving/still state machine (acceleration + fix speed + displacement, #895)+- com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt — when a "still" sender forces a one-off fix (#895) ### intents/ — assistant IPC - com/vayunmathur/findfamily/intents/GetIntent.kt - com/vayunmathur/findfamily/intents/CreateLinkIntent.kt@@ -56,6 +58,7 @@ WebSocket relay host: `wss://api.maproj.org/api/ws` (Cloudflare FIRST_PARTY pins - com/vayunmathur/findfamily/platform/FinalLocationReporter.kt - com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt - com/vayunmathur/findfamily/platform/PoweredOffBeacon.kt+- com/vayunmathur/findfamily/platform/LocationKeepAlive.kt — sender keep-alive: single fix intake, low-power/passive requests, forced fix (#895) ### service/ — Quick Settings tile - com/vayunmathur/findfamily/service/SharingTileService.kt ### tracker/ — BLE tracker protocol + powered-off finding
findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.ktnew file mode 100644index 0000000000..8f8755efc9--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/ForcedFixPolicy.kt@@ -0,0 +1,70 @@+package com.vayunmathur.findfamily.domain++/**+ * When the sending phone should ask for a one-off current location even+ * though nothing says it is moving (GitHub #895).+ *+ * Before #895 a "still" phone requested no location at all and the heartbeat+ * kept re-publishing the last held fix, so a missed departure froze the pin+ * for hours. Now the held fix may only get [intervalMs] old before the+ * service asks for a current location: network first (cheap), GPS only when+ * network cannot produce a fix fine enough to display.+ *+ * Pure: monotonic millisecond inputs only, no Android types.+ */+object ForcedFixPolicy {++    /** Held-fix age that triggers a forced fix while charging: power is not the constraint. */+    const val INTERVAL_CHARGING_MS = 5 * 60_000L++    /** Held-fix age that triggers a forced fix on battery. */+    const val INTERVAL_DEFAULT_MS = 10 * 60_000L++    /** Held-fix age that triggers a forced fix in power-save mode. */+    const val INTERVAL_POWER_SAVE_MS = 15 * 60_000L++    /** How long a forced network fix may take before giving up. */+    const val NETWORK_TIMEOUT_MS = 20_000L++    /** How long a forced GPS fix may take before giving up (bounds the GPS-on time). */+    const val GPS_TIMEOUT_MS = 30_000L++    /** The forced-fix interval for the current power state. Charging wins over power-save. */+    fun intervalMs(charging: Boolean, powerSave: Boolean): Long = when {+        charging -> INTERVAL_CHARGING_MS+        powerSave -> INTERVAL_POWER_SAVE_MS+        else -> INTERVAL_DEFAULT_MS+    }++    /**+     * True when the held fix (or the lack of one) is stale enough to force a+     * fix, and the previous attempt was at least one interval ago — a phone+     * in a basement must not retry GPS every heartbeat tick.+     */+    fun isDue(nowMs: Long, heldFixElapsedMs: Long?, lastAttemptMs: Long?, intervalMs: Long): Boolean {+        val heldStale = heldFixElapsedMs == null || nowMs - heldFixElapsedMs >= intervalMs+        val attemptGapOk = lastAttemptMs == null || nowMs - lastAttemptMs >= intervalMs+        return heldStale && attemptGapOk+    }++    /**+     * Whether to follow the network attempt with GPS.+     *+     * GPS runs when there is no network provider at all, or when network gave+     * nothing usable for display (no fix, or coarser than the display gate) —+     * except in power-save, where the existing policy keeps GPS to the moving+     * path only. A coarse network fix still reaches the movement detector+     * either way.+     */+    fun shouldFallBackToGps(+        hasGps: Boolean,+        hasNetwork: Boolean,+        networkAccuracyMeters: Double?,+        powerSave: Boolean,+    ): Boolean {+        if (!hasGps) return false+        if (!hasNetwork) return true+        if (powerSave) return false+        return networkAccuracyMeters == null || !NoShowPolicy.isAccurateEnough(networkAccuracyMeters)+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/domain/MovementDetector.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/MovementDetector.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/MovementDetector.ktnew file mode 100644index 0000000000..ef74c877ac--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/MovementDetector.kt@@ -0,0 +1,182 @@+package com.vayunmathur.findfamily.domain++/**+ * One location fix, reduced to what movement detection needs.+ *+ * Pure on purpose (no `android.location` types) so the state machine below is+ * unit-testable without a device. [accuracyMeters], [speedMps] and+ * [speedAccuracyMps] are null when the provider did not report them.+ */+data class FixSample(+    val latitude: Double,+    val longitude: Double,+    val accuracyMeters: Double?,+    val speedMps: Double?,+    val speedAccuracyMps: Double?,+    val elapsedMs: Long,+)++/** What a [MovementDetector] input changed, so the caller knows which radios to switch. */+enum class MotionTransition { NONE, BECAME_MOVING, BECAME_STILL }++/**+ * Decides whether the sending phone is moving (GitHub #895).+ *+ * The old rule was acceleration alone: 60 s of linear acceleration under+ * [ACCELERATION_THRESHOLD] meant "still", and only the one-shot+ * significant-motion sensor could undo it. A car, bus or tram at steady speed+ * sits under that threshold, and the significant-motion sensor is step-driven+ * on many phones, so a departure by vehicle was never noticed and the phone+ * stopped producing fixes for hours.+ *+ * Now any of three kinds of evidence keeps or makes the phone "moving":+ * - acceleration above [ACCELERATION_THRESHOLD] (unchanged),+ * - a fix whose provider-reported speed is clearly above walking pace,+ * - a fix displaced from the last reference point ([anchor]) by more than+ *   [DISPLACEMENT_THRESHOLD_METERS] AND by more than [ERROR_RADIUS_SCALE]+ *   times both fixes' error radii combined, so network jitter at home does+ *   not count but a coarse fix far from home does.+ *+ * Fixes of any accuracy feed this detector, including ones the display gate+ * ([NoShowPolicy.NO_SHOW_MAX_ACCURACY_METERS]) drops: a 600 m network fix+ * two kilometres from home cannot say where the person is, but it does prove+ * they left.+ *+ * "Still" now needs both signals quiet: no acceleration for+ * [ACCELERATION_QUIET_MS] AND no fix-based movement for [FIX_QUIET_MS].+ *+ * Times are monotonic milliseconds (elapsedRealtime) supplied by the caller.+ */+class MovementDetector {++    /** True while active (10 s network / GPS) updates should run. */+    var isMoving: Boolean = false+        private set++    /** Last time acceleration (or a wake-up such as significant motion) showed movement. */+    var lastAccelerationMovementMs: Long = 0L+        private set++    /** Last time a fix (speed or displacement) showed movement. */+    var lastFixMovementMs: Long = 0L+        private set++    /** Reference point displacement is measured from; moves only on movement or refinement. */+    var anchor: FixSample? = null+        private set++    /**+     * Something outside the fix stream says "moving": the significant-motion+     * trigger, a fresh service start with no fix, or the pre-unlock path.+     * Both quiet windows restart, so the phone gets a full window of active+     * updates to gather evidence before it may count as still again.+     */+    fun markMoving(nowMs: Long): MotionTransition {+        lastAccelerationMovementMs = nowMs+        lastFixMovementMs = nowMs+        return becomeMoving()+    }++    /** Feed one linear-acceleration magnitude (m/s²). */+    fun onAcceleration(magnitude: Float, nowMs: Long): MotionTransition {+        if (magnitude > ACCELERATION_THRESHOLD) {+            lastAccelerationMovementMs = nowMs+            return becomeMoving()+        }+        return evaluateStillness(nowMs)+    }++    /**+     * Feed one fix, whatever its accuracy. Fixes older than [MAX_SAMPLE_AGE_MS]+     * at [nowMs] (a cached fix replayed by a provider) are ignored entirely.+     */+    fun onFix(sample: FixSample, nowMs: Long): MotionTransition {+        if (nowMs - sample.elapsedMs > MAX_SAMPLE_AGE_MS) return evaluateStillness(nowMs)+        val moved = isFastEnough(sample) || isDisplaced(sample)+        val held = anchor+        if (held == null || moved || accuracyOf(sample) < accuracyOf(held)) {+            // Movement moves the reference point; a consistent but sharper fix+            // refines it (otherwise a coarse first anchor would hide a slow walk).+            anchor = sample+        }+        if (moved) {+            lastFixMovementMs = nowMs+            return becomeMoving()+        }+        return evaluateStillness(nowMs)+    }++    /** Re-check stillness with no new input (heartbeat tick, devices without an accelerometer). */+    fun onTick(nowMs: Long): MotionTransition = evaluateStillness(nowMs)++    private fun becomeMoving(): MotionTransition {+        if (isMoving) return MotionTransition.NONE+        isMoving = true+        return MotionTransition.BECAME_MOVING+    }++    private fun evaluateStillness(nowMs: Long): MotionTransition {+        if (!isMoving) return MotionTransition.NONE+        val accelerationQuiet = nowMs - lastAccelerationMovementMs > ACCELERATION_QUIET_MS+        val fixesQuiet = nowMs - lastFixMovementMs > FIX_QUIET_MS+        if (!accelerationQuiet || !fixesQuiet) return MotionTransition.NONE+        isMoving = false+        return MotionTransition.BECAME_STILL+    }++    private fun isFastEnough(sample: FixSample): Boolean {+        val speed = sample.speedMps ?: return false+        if (!speed.isFinite()) return false+        val uncertainty = sample.speedAccuracyMps?.takeIf { it.isFinite() && it >= 0.0 } ?: 0.0+        return speed - uncertainty > WALKING_SPEED_MPS+    }++    private fun isDisplaced(sample: FixSample): Boolean {+        val held = anchor ?: return false+        val distance = NoShowPolicy.haversineMeters(+            held.latitude, held.longitude, sample.latitude, sample.longitude+        )+        return distance > DISPLACEMENT_THRESHOLD_METERS &&+            distance > ERROR_RADIUS_SCALE * (accuracyOf(held) + accuracyOf(sample))+    }++    private fun accuracyOf(sample: FixSample): Double =+        sample.accuracyMeters?.takeIf { it.isFinite() && it >= 0.0 } ?: UNKNOWN_ACCURACY_METERS++    /** Tuning constants; see the class KDoc for how they combine. */+    companion object {+        /** Linear-acceleration magnitude that counts as movement (unchanged from before #895). */+        const val ACCELERATION_THRESHOLD = 0.5f++        /** How long acceleration must stay under the threshold before "still" is possible. */+        const val ACCELERATION_QUIET_MS = 60_000L++        /**+         * How long fixes must show no movement before "still" is possible.+         *+         * Longer than the power-save GPS interval (180 s) so a vehicle tracked+         * only by GPS speed in power-save does not flap between modes.+         */+        const val FIX_QUIET_MS = 4 * 60_000L++        /** Brisk walking is ~1.7 m/s; anything clearly above 2 m/s is a vehicle or a run. */+        const val WALKING_SPEED_MPS = 2.0++        /** Minimum displacement that can count as movement, on top of the error-radius test. */+        const val DISPLACEMENT_THRESHOLD_METERS = 75.0++        /**+         * Android accuracy is a ~68 % radius; doubling it gives roughly a 95 %+         * radius, so two fixes only disagree when their 95 % circles do not+         * overlap. Keeps the at-home network jitter from issue #895 from+         * waking active updates over and over.+         */+        const val ERROR_RADIUS_SCALE = 2.0++        /** Error radius assumed for a fix that reports none: treat it as coarse. */+        const val UNKNOWN_ACCURACY_METERS = 1_000.0++        /** Fixes older than this when they arrive say nothing about movement now. */+        const val MAX_SAMPLE_AGE_MS = 2 * 60_000L+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.ktnew file mode 100644index 0000000000..a22a9571ed--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/LocationKeepAlive.kt@@ -0,0 +1,223 @@+package com.vayunmathur.findfamily.platform++import android.location.Location+import android.location.LocationManager+import android.os.CancellationSignal+import android.os.SystemClock+import com.vayunmathur.findfamily.domain.FixSample+import com.vayunmathur.findfamily.domain.ForcedFixPolicy+import com.vayunmathur.findfamily.util.LocationTrackingService+import com.vayunmathur.findfamily.util.recordFix+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import java.util.concurrent.Executor+import kotlin.coroutines.resume++/*+ * Sender keep-alive for GitHub #895 ("the locations of loved ones aren't updating").+ *+ * The sending phone used to request no location at all once it decided it was "still",+ * and only the one-shot significant-motion sensor could wake it. In a vehicle that sensor+ * often never fires, so the phone kept re-publishing a fix from hours earlier. Three+ * pieces here make sure a "still" phone keeps producing fresh fixes:+ *+ * 1. An always-on low-power NETWORK request (minutes apart, displacement-filtered) and a+ *    PASSIVE request, so leaving by any means delivers a fix that flips the phone back to+ *    moving through [onLocationFix].+ * 2. A periodic forced fix ([ForcedFixPolicy]) when the held fix gets old.+ * 3. A single fix intake that lets every fix, however coarse, reach the movement detector+ *    before the display accuracy gate in [recordFix] decides whether it is held.+ *+ * All of it runs on the main thread except the forced-fix wait itself.+ */++private const val TAG_KEEP_ALIVE = "FF-KeepAlive"+private const val NANOS_PER_MILLI = 1_000_000L++/** Low-power NETWORK interval on battery. Network fixes are cheap (no GPS radio). */+internal const val LOW_POWER_INTERVAL_MS = 3 * 60_000L++/** Low-power NETWORK interval in power-save mode. */+internal const val LOW_POWER_INTERVAL_POWER_SAVE_MS = 5 * 60_000L++/**+ * Displacement filter on the low-power request: a stationary phone gets no deliveries+ * (the forced fix keeps it fresh), a phone that has left gets one within minutes.+ */+internal const val LOW_POWER_MIN_DISTANCE_METERS = 75f++/** PASSIVE costs nothing (other apps' fixes); the interval only bounds callback rate. */+internal const val PASSIVE_MIN_INTERVAL_MS = 30_000L++/** Supplies one current fix from a provider, or null on timeout or failure. */+internal fun interface CurrentLocationSource {+    suspend fun current(provider: String, timeoutMs: Long): Location?+}++/** [CurrentLocationSource] over LocationManager.getCurrentLocation (API 30+). */+internal class PlatformCurrentLocationSource(+    private val locationManager: LocationManager,+    private val executor: Executor,+) : CurrentLocationSource {+    // Permission revoked or provider missing: no fix, never a crash.+    override suspend fun current(provider: String, timeoutMs: Long): Location? =+        withTimeoutOrNull(timeoutMs) {+            suspendCancellableCoroutine { continuation ->+                val signal = CancellationSignal()+                continuation.invokeOnCancellation { signal.cancel() }+                try {+                    locationManager.getCurrentLocation(provider, signal, executor) { location ->+                        if (continuation.isActive) continuation.resume(location)+                    }+                } catch (_: SecurityException) {+                    continuation.resume(null)+                } catch (_: IllegalArgumentException) {+                    continuation.resume(null)+                }+            }+        }+}++/** The platform fix reduced to what [com.vayunmathur.findfamily.domain.MovementDetector] needs. */+internal fun Location.toFixSample(): FixSample = FixSample(+    latitude = latitude,+    longitude = longitude,+    accuracyMeters = if (hasAccuracy()) accuracy.toDouble() else null,+    speedMps = if (hasSpeed()) speed.toDouble() else null,+    speedAccuracyMps = if (hasSpeedAccuracy()) speedAccuracyMetersPerSecond.toDouble() else null,+    elapsedMs = elapsedRealtimeNanos / NANOS_PER_MILLI,+)++/**+ * The one intake for every fix, from every listener and the forced fix.+ *+ * Movement detection sees the fix first, whatever its accuracy: a coarse fix far from+ * where the phone was still proves it left. Only then does [recordFix] apply the+ * display gate (fixes worse than NoShowPolicy's 100 m are never held or published).+ */+internal fun LocationTrackingService.onLocationFix(location: Location) {+    val transition = motion.onFix(location.toFixSample(), SystemClock.elapsedRealtime())+    recordFix(location)+    applyMotionTransition(transition)+}++/**+ * Runs on every heartbeat tick (30 s while the CPU is awake) on the main thread:+ * re-checks stillness, keeps the low-power requests registered, and starts a forced+ * fix when one is due.+ */+internal fun LocationTrackingService.keepAliveTick() {+    applyMotionTransition(motion.onTick(SystemClock.elapsedRealtime()))+    refreshLowPowerUpdates()+    maybeRequestForcedFix()+}++/**+ * Registers (or re-registers, when power-save toggles) the low-power NETWORK request,+ * and the PASSIVE request once. Requests survive provider disable/enable, so a provider+ * that is off now is simply retried on a later tick.+ */+internal fun LocationTrackingService.refreshLowPowerUpdates() {+    val wanted = if (powerManager.isPowerSaveMode) LOW_POWER_INTERVAL_POWER_SAVE_MS else LOW_POWER_INTERVAL_MS+    if (lowPowerIntervalMs != wanted &&+        locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)+    ) {+        lowPowerIntervalMs = try {+            locationManager.removeUpdates(lowPowerListener)+            locationManager.requestLocationUpdates(+                LocationManager.NETWORK_PROVIDER,+                wanted,+                LOW_POWER_MIN_DISTANCE_METERS,+                mainExecutor,+                lowPowerListener,+            )+            wanted+        } catch (_: SecurityException) {+            0L+        } catch (_: IllegalArgumentException) {+            0L+        }+    }+    if (!passiveRequested) {+        passiveRequested = try {+            locationManager.requestLocationUpdates(+                LocationManager.PASSIVE_PROVIDER,+                PASSIVE_MIN_INTERVAL_MS,+                0f,+                mainExecutor,+                passiveListener,+            )+            true+        } catch (_: SecurityException) {+            false+        } catch (_: IllegalArgumentException) {+            false+        }+    }+}++/** Drops the low-power and passive requests (service teardown). */+internal fun LocationTrackingService.stopLowPowerUpdates() {+    locationManager.removeUpdates(lowPowerListener)+    locationManager.removeUpdates(passiveListener)+    lowPowerIntervalMs = 0L+    passiveRequested = false+    forcedFixJob?.cancel()+    forcedFixJob = null+}++private fun LocationTrackingService.isCharging(): Boolean = runCatching { bm.isCharging }.getOrDefault(false)++/**+ * True (and the attempt recorded) when the held fix is stale enough for a forced fix.+ * See [ForcedFixPolicy.isDue]; never while a previous forced fix is still running.+ */+internal fun LocationTrackingService.forcedFixDue(nowMs: Long): Boolean {+    if (forcedFixJob?.isActive == true) return false+    val interval = ForcedFixPolicy.intervalMs(isCharging(), powerManager.isPowerSaveMode)+    val heldMs = lastKnownLocation?.let { it.elapsedRealtimeNanos / NANOS_PER_MILLI }+    if (!ForcedFixPolicy.isDue(nowMs, heldMs, lastForcedFixAttemptMs, interval)) return false+    lastForcedFixAttemptMs = nowMs+    return true+}++/** Starts a forced fix in the background when [forcedFixDue]. */+internal fun LocationTrackingService.maybeRequestForcedFix() {+    if (!forcedFixDue(SystemClock.elapsedRealtime())) return+    forcedFixJob = serviceScope.launch { runForcedFix() }+}++/**+ * One forced fix: network first; GPS after it only when network gave nothing fine+ * enough to display ([ForcedFixPolicy.shouldFallBackToGps]). Each result goes through+ * [onLocationFix], so a coarse network answer can still wake movement detection.+ */+internal suspend fun LocationTrackingService.runForcedFix() {+    val source = currentLocationSourceOverride ?: PlatformCurrentLocationSource(locationManager, mainExecutor)+    val hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)+    val hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)+    val powerSave = powerManager.isPowerSaveMode+    val network = if (hasNetwork) {+        source.current(LocationManager.NETWORK_PROVIDER, ForcedFixPolicy.NETWORK_TIMEOUT_MS)+    } else {+        null+    }+    network?.let { deliverForcedFix(it) }+    val networkAccuracy = network?.takeIf { it.hasAccuracy() }?.accuracy?.toDouble()+    if (ForcedFixPolicy.shouldFallBackToGps(hasGps, hasNetwork, networkAccuracy, powerSave)) {+        val gps = source.current(LocationManager.GPS_PROVIDER, ForcedFixPolicy.GPS_TIMEOUT_MS)+        gps?.let { deliverForcedFix(it) }+        val gpsResult = if (gps != null) "ok" else "none"+        Log.status(TAG_KEEP_ALIVE, "forced fix: network acc=$networkAccuracy, gps $gpsResult")+    } else {+        Log.status(TAG_KEEP_ALIVE, "forced fix: network acc=$networkAccuracy")+    }+}++private suspend fun LocationTrackingService.deliverForcedFix(location: Location) {+    withContext(Dispatchers.Main.immediate) { onLocationFix(location) }+}
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.ktindex 3240206ef3..ab7893b31d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingDirectBoot.kt@@ -12,6 +12,7 @@ import com.vayunmathur.findfamily.R import com.vayunmathur.findfamily.data.Coord import com.vayunmathur.findfamily.data.DirectBootStore import com.vayunmathur.findfamily.data.LocationValue+import com.vayunmathur.findfamily.platform.keepAliveTick import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers@@ -39,7 +40,10 @@ internal fun LocationTrackingService.startDirectBootTracking() {         // Expected on the first boot after this ships, and after a factory reset: there is         // nothing to publish with yet. Seeding happens below once the user unlocks.         if (!DirectBootStore.isSeeded(ctx)) {-            Log.status(LocationTrackingService.TAG_DIRECT_BOOT, "no device-protected mirror yet; idle until first unlock")+            Log.status(+                LocationTrackingService.TAG_DIRECT_BOOT,+                "no device-protected mirror yet; idle until first unlock"+            )             return@launch         }         if (!DirectBootStore.isTrackingEnabled(ctx)) {@@ -53,9 +57,7 @@ internal fun LocationTrackingService.startDirectBootTracking() {          withContext(Dispatchers.Main) {             registerSensors()-            isMoving = true-            lastMovementTime = System.currentTimeMillis()-            setupLocationUpdates()+            startMovingNow()         }         // Inbound delivery needs Room to persist anything, so the pre-unlock socket is         // publish-only. Peers' locations are picked up on reconnect after unlock.@@ -64,8 +66,13 @@ internal fun LocationTrackingService.startDirectBootTracking() {         val sharing = DirectBootStore.isGlobalSharingEnabled(ctx)         val targets = if (sharing) DirectBootStore.roster(ctx) else emptyList()         publishRoster = targets-        Log.status(LocationTrackingService.TAG_DIRECT_BOOT, "running pre-unlock, sharing=$sharing targets=${targets.size}")+        Log.status(+            LocationTrackingService.TAG_DIRECT_BOOT,+            "running pre-unlock, sharing=$sharing targets=${targets.size}"+        )         while (isActive) {+            // Same sender keep-alive as the unlocked heartbeat (#895).+            withContext(Dispatchers.Main) { keepAliveTick() }             publishDirectBoot(targets)             delay(30.seconds)         }
findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.ktindex 91e1da4240..f57eeccf4d 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -52,7 +52,13 @@ import com.vayunmathur.findfamily.data.TemporaryLink import com.vayunmathur.findfamily.data.User import com.vayunmathur.findfamily.data.Waypoint import com.vayunmathur.findfamily.data.havershine+import com.vayunmathur.findfamily.domain.MotionTransition+import com.vayunmathur.findfamily.domain.MovementDetector+import com.vayunmathur.findfamily.platform.CurrentLocationSource import com.vayunmathur.findfamily.platform.FinalLocationReporter+import com.vayunmathur.findfamily.platform.onLocationFix+import com.vayunmathur.findfamily.platform.keepAliveTick+import com.vayunmathur.findfamily.platform.stopLowPowerUpdates import com.vayunmathur.findfamily.uwb.UwbEnvelope import com.vayunmathur.findfamily.uwb.UwbEnvelopeKind import com.vayunmathur.findfamily.uwb.UwbInbox@@ -91,23 +97,17 @@ import kotlin.time.Duration.Companion.seconds  class LocationTrackingService : Service(), SensorEventListener {     internal val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)-    private lateinit var locationManager: LocationManager+    internal lateinit var locationManager: LocationManager     private lateinit var sensorManager: SensorManager-    private lateinit var powerManager: PowerManager+    internal lateinit var powerManager: PowerManager     private var accelerometer: Sensor? = null     private var significantMotionSensor: Sensor? = null +    // One extra wake-up source, no longer the only one (#895): fixes from the always-on+    // low-power request and the periodic forced fix can also flip the phone to moving.     private val triggerEventListener = object : TriggerEventListener() {         override fun onTrigger(event: TriggerEvent?) {-            isMoving = true-            lastMovementTime = System.currentTimeMillis()-            serviceScope.launch(Dispatchers.Main) {-                setupLocationUpdates()-            }-            // Start monitoring for stillness-            accelerometer?.let {-                sensorManager.registerListener(this@LocationTrackingService, it, SensorManager.SENSOR_DELAY_NORMAL)-            }+            serviceScope.launch(Dispatchers.Main) { startMovingNow() }         }     } @@ -120,10 +120,38 @@ class LocationTrackingService : Service(), SensorEventListener {     internal lateinit var bm: BatteryManager          private var isGpsRunning = false-    internal var isMoving = false-    internal var lastMovementTime = 0L+    private var accelerometerRegistered = false     internal var lastKnownLocation: Location? = null +    /**+     * Moving/still state machine (#895): acceleration, fix speed and fix displacement all+     * count, so a car or tram at steady speed stays "moving". See [MovementDetector].+     */+    internal val motion = MovementDetector()++    /** True while active (10 s network / GPS) updates run; owned by [motion]. */+    internal val isMoving: Boolean get() = motion.isMoving++    // Sender keep-alive (#895). The logic lives in platform/LocationKeepAlive.kt; the state+    // lives here because it is per-service-instance.++    /** Always-on coarse NETWORK request; catches departures while "still". */+    internal val lowPowerListener = LocationListener { onLocationFix(it) }++    /** PASSIVE request: free fixes other apps (e.g. navigation) already paid for. */+    internal val passiveListener = LocationListener { onLocationFix(it) }++    /** Interval of the current low-power request, or 0 when none is registered. */+    internal var lowPowerIntervalMs = 0L+    internal var passiveRequested = false++    /** elapsedRealtime of the last forced-fix attempt, or null before the first one. */+    internal var lastForcedFixAttemptMs: Long? = null+    internal var forcedFixJob: Job? = null++    /** Test seam: replaces LocationManager.getCurrentLocation for the forced fix. */+    internal var currentLocationSourceOverride: CurrentLocationSource? = null+     /**      * Monotonic timestamp (elapsedRealtime) of the last fix delivered by      * NETWORK_PROVIDER since the current request, or 0 if none has arrived yet.@@ -186,7 +214,7 @@ class LocationTrackingService : Service(), SensorEventListener {      private val networkListener = LocationListener { location ->         lastNetworkFixElapsedMs = SystemClock.elapsedRealtime()-        recordFix(location)+        onLocationFix(location)         if (!location.hasAccuracy() || location.accuracy > MAX_FIX_ACCURACY_METERS) {             if (!isGpsRunning && isMoving) startGps()         } else {@@ -194,7 +222,7 @@ class LocationTrackingService : Service(), SensorEventListener {         }     }     private val gpsListener = LocationListener { location ->-        recordFix(location)+        onLocationFix(location)     }      // The heartbeat and fix selection live in LocationTrackingHeartbeat.kt.@@ -209,25 +237,53 @@ class LocationTrackingService : Service(), SensorEventListener {             val y = event.values[1]             val z = event.values[2]             val accel = sqrt(x*x + y*y + z*z)-            if (accel > MOVEMENT_ACCELERATION_THRESHOLD) {-                lastMovementTime = System.currentTimeMillis()-                if (!isMoving) {-                    isMoving = true-                    setupLocationUpdates()-                }-            } else {-                if (isMoving && (System.currentTimeMillis() - lastMovementTime > STILLNESS_TIMEOUT_MS)) {-                    isMoving = false-                    stopTrackingUpdates()-                    if (significantMotionSensor != null) {-                        sensorManager.unregisterListener(this, accelerometer)-                        requestSignificantMotion()-                    }+            // Low acceleration alone no longer means "still": the detector also+            // needs the recent fixes to show no speed or displacement (#895).+            applyMotionTransition(motion.onAcceleration(accel, SystemClock.elapsedRealtime()))+        }+    }++    /** Something outside the fix stream says "moving" (significant motion, no fix yet). */+    internal fun startMovingNow() {+        motion.markMoving(SystemClock.elapsedRealtime())+        setupLocationUpdates()+        registerAccelerometer()+    }++    /** Switches the radios for a [MovementDetector] verdict. Main thread. */+    internal fun applyMotionTransition(transition: MotionTransition) {+        when (transition) {+            MotionTransition.BECAME_MOVING -> {+                Log.status(TAG_MOTION, "moving: starting active location updates")+                setupLocationUpdates()+                // Watch for stillness again (it was unregistered when the phone went still).+                registerAccelerometer()+            }+            MotionTransition.BECAME_STILL -> {+                Log.status(TAG_MOTION, "still: active updates off, low-power request stays on")+                stopTrackingUpdates()+                if (significantMotionSensor != null) {+                    unregisterAccelerometer()+                    requestSignificantMotion()                 }             }+            MotionTransition.NONE -> Unit         }     } +    private fun registerAccelerometer() {+        if (accelerometerRegistered || !::sensorManager.isInitialized) return+        val sensor = accelerometer ?: return+        accelerometerRegistered =+            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)+    }++    private fun unregisterAccelerometer() {+        if (!accelerometerRegistered) return+        sensorManager.unregisterListener(this, accelerometer)+        accelerometerRegistered = false+    }+     override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}      override fun onBind(intent: Intent): IBinder? {@@ -332,14 +388,10 @@ class LocationTrackingService : Service(), SensorEventListener {                 withContext(Dispatchers.Main) {                     registerSensors()                     // If we don't have any recent location (e.g. fresh start or recovery-                    // from a crash), force isMoving = true so setupLocationUpdates()+                    // from a crash), start moving so setupLocationUpdates()                     // immediately starts requesting GPS instead of waiting for the                     // significant-motion sensor to trigger.-                    if (lastKnownLocation == null) {-                        isMoving = true-                        lastMovementTime = System.currentTimeMillis()-                    }-                    setupLocationUpdates()+                    if (lastKnownLocation == null) startMovingNow() else setupLocationUpdates()                 }                 trackingInitialized = true             }@@ -356,6 +408,9 @@ class LocationTrackingService : Service(), SensorEventListener {                         withContext(Dispatchers.Main) { stopSelf() }                         break                     }+                    // Stillness re-check, low-power request upkeep and the periodic+                    // forced fix (#895). Main thread: it owns the motion state.+                    withContext(Dispatchers.Main) { keepAliveTick() }                     syncHeartbeat()                     try {                         seedDirectBootMirror()@@ -403,8 +458,12 @@ class LocationTrackingService : Service(), SensorEventListener {         if (significantMotionSensor != null) {             requestSignificantMotion()         } else {-            sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL)+            registerAccelerometer()         }+        // Never fully dark while "still" (#895): a coarse network request with a+        // displacement filter plus a passive request, both kept for the service's life.+        // Updated (power-save interval) on every keepAliveTick().+        keepAliveTick()     }      private fun requestSignificantMotion() {@@ -530,6 +589,7 @@ class LocationTrackingService : Service(), SensorEventListener {         internal const val TAG_DIRECT_BOOT = "FF-DirectBoot"         internal const val TAG_POWERED_OFF = "FF-PoweredOff"         internal const val TAG_NETWORK_ASSIST = "FF-NetworkAssist"+        internal const val TAG_MOTION = "FF-Motion"          /**          * How long NETWORK_PROVIDER may go without delivering any fix before GPS@@ -541,12 +601,6 @@ class LocationTrackingService : Service(), SensorEventListener {          */         internal const val NETWORK_NO_LOCK_TIMEOUT_MS = 60_000L -        /** Acceleration magnitude that counts as movement on the linear-acceleration sensor. */-        internal const val MOVEMENT_ACCELERATION_THRESHOLD = 0.5f--        /** How long low acceleration must persist before the device counts as still. */-        internal const val STILLNESS_TIMEOUT_MS = 60_000L-         /** How often to drain powered-off sightings. See [LocationTrackingService.pollPoweredOffSightings]. */         internal const val POWERED_OFF_POLL_INTERVAL_MS = 5 * 60 * 1000L @@ -604,6 +658,7 @@ class LocationTrackingService : Service(), SensorEventListener {         }         if (::locationManager.isInitialized) {             stopTrackingUpdates()+            stopLowPowerUpdates()         }         stopForeground(STOP_FOREGROUND_REMOVE)     }
findfamily/src/test/java/com/vayunmathur/findfamily/domain/MovementDetectorTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/domain/MovementDetectorTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/MovementDetectorTest.ktnew file mode 100644index 0000000000..576906cdab--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/domain/MovementDetectorTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.findfamily.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** GitHub #895: the sender's moving/still state machine and its forced-fix policy. */+class MovementDetectorTest {++    private val homeLat = 51.5+    private val homeLon = -0.12++    /** ~111 km per degree of latitude. */+    private fun northOf(meters: Double) = homeLat + meters / 111_195.0++    private fun fix(+        lat: Double = homeLat,+        lon: Double = homeLon,+        acc: Double? = 10.0,+        speed: Double? = null,+        speedAcc: Double? = null,+        at: Long,+    ) = FixSample(lat, lon, acc, speed, speedAcc, at)++    private val minute = 60_000L++    /** A detector that has gone still at home, anchored on an accurate fix. */+    private fun stillAtHome(): Pair<MovementDetector, Long> {+        val d = MovementDetector()+        d.markMoving(0L)+        d.onFix(fix(at = 0L), 0L)+        val t = MovementDetector.FIX_QUIET_MS + minute+        assertEquals(MotionTransition.BECAME_STILL, d.onTick(t))+        assertFalse(d.isMoving)+        return d to t+    }++    @Test+    fun vehicleWithLowAccelerationButDisplacementStaysMoving() {+        val d = MovementDetector()+        d.markMoving(0L)+        // Steady tram ride: acceleration never above 0.5 m/s², fixes 600 m apart, no speed.+        var t = 0L+        var meters = 0.0+        repeat(30) {+            for (s in 0 until 60) {+                assertEquals(MotionTransition.NONE, d.onAcceleration(0.1f, t + s * 1_000L))+            }+            t += minute+            meters += 600.0+            assertEquals(MotionTransition.NONE, d.onFix(fix(lat = northOf(meters), at = t), t))+        }+        assertTrue(d.isMoving, "30 min of displacement must keep the phone moving")+    }++    @Test+    fun vehicleSpeedFromAnyProviderWakesAStillPhone() {+        val (d, t) = stillAtHome()+        // Same spot (no displacement) but the provider reports 12 m/s.+        val fast = fix(speed = 12.0, speedAcc = 1.0, at = t)+        assertEquals(MotionTransition.BECAME_MOVING, d.onFix(fast, t))+        assertTrue(d.isMoving)+    }++    @Test+    fun walkingPaceOrUncertainSpeedDoesNotCountAsVehicle() {+        val (d, t) = stillAtHome()+        assertEquals(MotionTransition.NONE, d.onFix(fix(speed = 1.4, at = t), t))+        // 3 m/s reading with ±2 m/s uncertainty is not clearly above walking.+        assertEquals(MotionTransition.NONE, d.onFix(fix(speed = 3.0, speedAcc = 2.0, at = t + 1), t + 1))+        assertFalse(d.isMoving)+    }++    @Test+    fun coarseFixFarFromHomeWakesMovementDetection() {+        val (d, t) = stillAtHome()+        // 600 m network fix, 3 km away: too coarse to display, but proves departure.+        val coarse = fix(lat = northOf(3_000.0), acc = 600.0, at = t)+        assertEquals(MotionTransition.BECAME_MOVING, d.onFix(coarse, t))+        assertEquals(coarse, d.anchor)+    }++    @Test+    fun networkJitterAtHomeDoesNotWakeMovement() {+        val (d, t) = stillAtHome()+        // 110 m off with a 50 m claimed radius: within 2 x (10 + 50) = 120 m, so no.+        assertEquals(MotionTransition.NONE, d.onFix(fix(lat = northOf(110.0), acc = 50.0, at = t), t))+        // A coarse fix wobbling 400 m with a 300 m radius does not count either.+        val wobble = fix(lat = northOf(400.0), acc = 300.0, at = t + 1)+        assertEquals(MotionTransition.NONE, d.onFix(wobble, t + 1))+        assertFalse(d.isMoving)+    }++    @Test+    fun stationaryPhoneGoesStillOnlyWhenBothSignalsAreQuiet() {+        val d = MovementDetector()+        d.markMoving(0L)+        d.onFix(fix(at = 0L), 0L)+        // Acceleration quiet for 61 s: the old rule would stop here.+        assertEquals(MotionTransition.NONE, d.onAcceleration(0.1f, 61_000L))+        assertTrue(d.isMoving, "acceleration alone must not decide still")+        // Fixes at the same spot keep arriving; still only after the fix window too.+        assertEquals(MotionTransition.NONE, d.onFix(fix(at = 2 * minute), 2 * minute))+        val after = MovementDetector.FIX_QUIET_MS + 1+        assertEquals(MotionTransition.BECAME_STILL, d.onFix(fix(at = after), after))+        assertFalse(d.isMoving)+    }++    @Test+    fun accelerationStillWakesAndHoldsMovement() {+        val (d, t) = stillAtHome()+        assertEquals(MotionTransition.BECAME_MOVING, d.onAcceleration(2.0f, t))+        // Keeps moving while acceleration keeps coming, even with no fixes.+        val later = t + MovementDetector.FIX_QUIET_MS + minute+        assertEquals(MotionTransition.NONE, d.onAcceleration(1.0f, later))+        assertTrue(d.isMoving)+    }++    @Test+    fun replayedOldFixSaysNothing() {+        val (d, t) = stillAtHome()+        val old = fix(lat = northOf(5_000.0), at = t - MovementDetector.MAX_SAMPLE_AGE_MS - 1)+        assertEquals(MotionTransition.NONE, d.onFix(old, t))+        assertFalse(d.isMoving)+    }++    @Test+    fun coarseAnchorIsRefinedSoASlowDepartureIsStillSeen() {+        val d = MovementDetector()+        d.onFix(fix(acc = 800.0, at = 0L), 0L)+        // Accurate fix 300 m away is consistent with the coarse anchor and refines it.+        val sharp = fix(lat = northOf(300.0), acc = 10.0, at = 1L)+        assertEquals(MotionTransition.NONE, d.onFix(sharp, 1L))+        assertEquals(sharp, d.anchor)+        // 150 m on from the refined anchor now counts.+        assertEquals(MotionTransition.BECAME_MOVING, d.onFix(fix(lat = northOf(450.0), at = 2L), 2L))+    }++    @Test+    fun unknownAccuracyIsTreatedAsCoarse() {+        val (d, t) = stillAtHome()+        assertEquals(MotionTransition.NONE, d.onFix(fix(lat = northOf(1_500.0), acc = null, at = t), t))+        val far = fix(lat = northOf(3_000.0), acc = null, at = t + 1)+        assertEquals(MotionTransition.BECAME_MOVING, d.onFix(far, t + 1))+    }++    @Test+    fun forcedFixIntervalTightensWhileCharging() {+        val p = ForcedFixPolicy+        assertEquals(p.INTERVAL_CHARGING_MS, p.intervalMs(charging = true, powerSave = true))+        assertEquals(p.INTERVAL_POWER_SAVE_MS, p.intervalMs(charging = false, powerSave = true))+        assertEquals(p.INTERVAL_DEFAULT_MS, p.intervalMs(charging = false, powerSave = false))+        assertTrue(p.INTERVAL_CHARGING_MS < p.INTERVAL_DEFAULT_MS)+    }++    @Test+    fun staleHeldFixMakesForcedFixDue() {+        val i = ForcedFixPolicy.INTERVAL_DEFAULT_MS+        val now = 100 * minute+        fun due(held: Long?, attempt: Long?) = ForcedFixPolicy.isDue(now, held, attempt, i)+        assertTrue(due(held = null, attempt = null))+        assertFalse(due(held = now - i + 1, attempt = null))+        assertTrue(due(held = now - i, attempt = null))+        // A failed attempt one tick ago must not retry yet.+        assertFalse(due(held = null, attempt = now - 30_000L))+        assertTrue(due(held = null, attempt = now - i))+    }++    @Test+    fun gpsFallbackOnlyWhenNetworkCannotDisplay() {+        fun gps(hasGps: Boolean = true, hasNetwork: Boolean = true, acc: Double?, powerSave: Boolean = false) =+            ForcedFixPolicy.shouldFallBackToGps(hasGps, hasNetwork, acc, powerSave)+        assertTrue(gps(acc = null))+        assertTrue(gps(acc = 400.0))+        assertFalse(gps(acc = 40.0))+        // Power-save keeps GPS to the moving path, unless there is no network at all.+        assertFalse(gps(acc = 400.0, powerSave = true))+        assertTrue(gps(hasNetwork = false, acc = null, powerSave = true))+        assertFalse(gps(hasGps = false, hasNetwork = false, acc = null))+    }++    @Test+    fun newDetectorStartsStillWithNoAnchor() {+        val d = MovementDetector()+        assertFalse(d.isMoving)+        assertNull(d.anchor)+        assertEquals(MotionTransition.NONE, d.onTick(10 * minute))+    }+}
findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt
diff --git a/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.ktnew file mode 100644index 0000000000..1979486a47--- /dev/null+++ b/findfamily/src/test/java/com/vayunmathur/findfamily/platform/LocationKeepAliveTest.kt@@ -0,0 +1,202 @@+package com.vayunmathur.findfamily.platform++import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import android.os.BatteryManager+import android.os.SystemClock+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.findfamily.data.FFDatabase+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.domain.ForcedFixPolicy+import com.vayunmathur.findfamily.domain.MotionTransition+import com.vayunmathur.findfamily.domain.MovementDetector+import com.vayunmathur.findfamily.util.LocationTrackingService+import kotlinx.coroutines.cancel+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows.shadowOf+import org.robolectric.shadows.ShadowSystemClock+import java.time.Duration+import java.util.Collections+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * GitHub #895, service level: the sender keeps producing fixes while "still", a coarse fix+ * wakes movement detection, vehicle motion with low acceleration stays moving, and a stale+ * held fix forces a one-off fix. Built on the repositoryOverride seam from 56de52e9b plus+ * the currentLocationSourceOverride seam added for #895.+ */+@RunWith(AndroidJUnit4::class)+class LocationKeepAliveTest {++    private lateinit var db: FFDatabase+    private lateinit var service: LocationTrackingService+    private val ctx: Context get() = ApplicationProvider.getApplicationContext<Application>()++    /** Providers asked for a forced fix, in order, and what each answers. */+    private val forcedCalls: MutableList<String> = Collections.synchronizedList(mutableListOf())+    private var networkAnswer: Location? = null+    private var gpsAnswer: Location? = null++    private val homeLat = 51.5+    private val homeLon = -0.12+    private fun northOf(meters: Double) = homeLat + meters / 111_195.0++    private fun location(+        provider: String = LocationManager.GPS_PROVIDER,+        lat: Double = homeLat,+        acc: Float = 10f,+    ) = Location(provider).apply {+        latitude = lat+        longitude = homeLon+        accuracy = acc+        elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()+        time = System.currentTimeMillis()+    }++    private fun advance(ms: Long) = ShadowSystemClock.advanceBy(Duration.ofMillis(ms))++    @BeforeTest+    fun setup() {+        db = Room.inMemoryDatabaseBuilder(ctx, FFDatabase::class.java).allowMainThreadQueries().build()+        service = Robolectric.buildService(LocationTrackingService::class.java).create().get()+        service.repositoryOverride = FindFamilyRepository(ctx, db)+        // The service's own instance: the one registerSensors() will use.+        val lm = service.getSystemService(LocationManager::class.java)+        shadowOf(lm).setLocationEnabled(true)+        shadowOf(lm).setProviderEnabled(LocationManager.NETWORK_PROVIDER, true)+        shadowOf(lm).setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        shadowOf(lm).setProviderEnabled(LocationManager.PASSIVE_PROVIDER, true)+        service.currentLocationSourceOverride = CurrentLocationSource { provider, _ ->+            forcedCalls += provider+            if (provider == LocationManager.NETWORK_PROVIDER) networkAnswer else gpsAnswer+        }+        // A fresh held fix so registerSensors() does not start a forced fix of its own.+        service.lastKnownLocation = location()+        service.registerSensors()+        service.bm = ctx.getSystemService(BatteryManager::class.java)+    }++    @AfterTest+    fun teardown() {+        service.serviceScope.cancel()+        db.close()+    }++    @Test+    fun lowPowerAndPassiveRequestsAreRegisteredAtStartAndSurviveStillness() {+        assertEquals(LOW_POWER_INTERVAL_MS, service.lowPowerIntervalMs)+        assertTrue(service.passiveRequested)+        service.startMovingNow()+        assertTrue(service.isMoving)+        advance(MovementDetector.FIX_QUIET_MS + 60_000L)+        service.keepAliveTick()+        assertFalse(service.isMoving, "no acceleration, no displacement: still")+        // Never fully dark: the low-power request is still there.+        assertEquals(LOW_POWER_INTERVAL_MS, service.lowPowerIntervalMs)+        assertTrue(service.passiveRequested)+    }++    @Test+    fun powerSaveLengthensTheLowPowerInterval() {+        shadowOf(service.powerManager).setIsPowerSaveMode(true)+        service.refreshLowPowerUpdates()+        assertEquals(LOW_POWER_INTERVAL_POWER_SAVE_MS, service.lowPowerIntervalMs)+    }++    @Test+    fun coarseFixWakesMovementButIsNotHeldForDisplay() {+        advance(1_000L)+        val home = location()+        service.onLocationFix(home)+        assertFalse(service.isMoving)+        // Low-power network answer 3 km away with 600 m accuracy.+        val coarse = location(LocationManager.NETWORK_PROVIDER, lat = northOf(3_000.0), acc = 600f)+        service.onLocationFix(coarse)+        assertTrue(service.isMoving, "a coarse fix far from the anchor must wake movement detection")+        // The 100 m display gate still applies: the coarse fix is not held or published.+        assertSame(home, service.lastKnownLocation)+    }++    @Test+    fun vehicleWithLowAccelerationButDisplacementStaysMoving() {+        service.startMovingNow()+        service.onLocationFix(location())+        var meters = 0.0+        repeat(10) {+            advance(60_000L)+            meters += 600.0+            val now = SystemClock.elapsedRealtime()+            // The linear-acceleration path the sensor callback takes: smooth ride, 0.1 m/s².+            service.applyMotionTransition(service.motion.onAcceleration(0.1f, now))+            service.onLocationFix(location(lat = northOf(meters)))+            service.keepAliveTick()+            assertTrue(service.isMoving, "still moving after ${it + 1} min of displacement")+        }+        // The vehicle stops: once both quiet windows pass, the phone goes still.+        advance(MovementDetector.FIX_QUIET_MS + 1_000L)+        service.applyMotionTransition(service.motion.onTick(SystemClock.elapsedRealtime()))+        assertFalse(service.isMoving)+    }++    @Test+    fun staleHeldFixRequestsAForcedFixOncePerInterval() {+        assertFalse(service.forcedFixDue(SystemClock.elapsedRealtime()), "fresh fix: nothing due")+        advance(ForcedFixPolicy.INTERVAL_DEFAULT_MS)+        assertTrue(service.forcedFixDue(SystemClock.elapsedRealtime()))+        // The attempt is recorded: the next heartbeat tick does not retry.+        advance(30_000L)+        assertFalse(service.forcedFixDue(SystemClock.elapsedRealtime()))+    }++    @Test+    fun chargingTightensTheForcedFixInterval() {+        shadowOf(service.bm).setIsCharging(true)+        advance(ForcedFixPolicy.INTERVAL_CHARGING_MS)+        assertTrue(service.forcedFixDue(SystemClock.elapsedRealtime()))+    }++    @Test+    fun forcedFixFallsBackToGpsWhenNetworkIsTooCoarseToDisplay() = runBlocking {+        advance(ForcedFixPolicy.INTERVAL_DEFAULT_MS + 1_000L)+        networkAnswer = location(LocationManager.NETWORK_PROVIDER, acc = 500f)+        val gps = location(acc = 8f)+        gpsAnswer = gps+        service.runForcedFix()+        val expected = listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER)+        assertEquals(expected, forcedCalls.toList())+        assertSame(gps, service.lastKnownLocation, "the fresh GPS fix replaces the stale held one")+    }++    @Test+    fun forcedFixStopsAtNetworkWhenItIsGoodEnough() = runBlocking {+        advance(ForcedFixPolicy.INTERVAL_DEFAULT_MS + 1_000L)+        val network = location(LocationManager.NETWORK_PROVIDER, acc = 30f)+        networkAnswer = network+        service.runForcedFix()+        assertEquals(listOf(LocationManager.NETWORK_PROVIDER), forcedCalls.toList())+        assertSame(network, service.lastKnownLocation)+    }++    @Test+    fun coarseForcedFixFarAwayWakesMovementEvenWithoutAGpsFix() = runBlocking {+        service.onLocationFix(location())+        advance(ForcedFixPolicy.INTERVAL_DEFAULT_MS + 1_000L)+        networkAnswer = location(LocationManager.NETWORK_PROVIDER, lat = northOf(4_000.0), acc = 700f)+        gpsAnswer = null+        service.runForcedFix()+        assertTrue(service.isMoving)+        assertEquals(MotionTransition.NONE, service.motion.onTick(SystemClock.elapsedRealtime()))+    }+}