Skip to content

Colota - Android GPS Location tracker

fix(geofence): arm the zone heartbeat with an alarm instead of a coroutine (#605)

Max Dietrich6c81bbfd0279
diff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.md
index 69df2a74..275770cb 100644
--- a/apps/docs/docs/development/permissions.md
+++ b/apps/docs/docs/development/permissions.md
@@ -113,7 +113,7 @@ This allows Colota to show the system dialog asking to exempt the app from batte
android.permission.WAKE_LOCK
```
-Lets Colota briefly hold the CPU awake while it acquires a location fix for a stationary-profile heartbeat during Doze, and is used internally by WorkManager for auto-export and battery-recovery jobs. A normal permission - granted automatically, with no access to personal data.
+Lets Colota briefly hold the CPU awake when a heartbeat alarm fires during Doze. The stationary-profile heartbeat holds it while it acquires a location fix, and the geofence heartbeat while it writes and sends the zone-center point. It is also used internally by WorkManager for auto-export and battery-recovery jobs. Android grants this permission automatically and it gives no access to personal data.
## Revoking Permissions
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 212ba601..b5338861 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -47,7 +47,7 @@ Stops GPS after the device has been still for the configured time (default 1 min
Records a point at the geofence center at a set interval while paused inside the zone, as a synthetic fix that does not wake GPS. Useful as a proof-of-presence signal so your backend knows the device is still there.
-The point is always saved on the device, including in offline mode and when the server is unreachable. Sending it is separate: it goes out under your normal sync rules, so a Wi-Fi-only or SSID condition still governs the upload while the stay is recorded either way. The first point is recorded on zone entry, then one per interval. Minimum 1 minute, default 15.
+The point is always saved on the device, including in offline mode and when the server is unreachable. Sending it is separate: it goes out under your normal sync rules, so a Wi-Fi-only or SSID condition still governs the upload while the stay is recorded either way. The first point is recorded on zone entry, then one per interval. Minimum 1 minute, default 15. Treat the interval as a minimum rather than a schedule: Colota uses an inexact alarm so it does not need the exact-alarm permission, and Android delivers those late.
### Combined behavior
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index c60eff6e..7f18a083 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -126,6 +126,12 @@
android:enabled="true"
android:exported="false" />
+ <!-- Geofence heartbeat alarm receiver -->
+ <receiver
+ android:name=".service.GeofenceHeartbeatReceiver"
+ android:enabled="true"
+ android:exported="false" />
+
<!-- Tracking control receiver (Tasker / automation) -->
<receiver
android:name=".triggers.TrackingControlReceiver"
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/GeofenceHeartbeatReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/GeofenceHeartbeatReceiver.kt
new file mode 100644
index 00000000..203b2bdb
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/GeofenceHeartbeatReceiver.kt
@@ -0,0 +1,35 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import com.Colota.util.AppLogger
+
+/**
+ * Receives the geofence-heartbeat alarm and forwards it to [LocationForegroundService] as
+ * ACTION_GEOFENCE_HEARTBEAT. The alarm targets this receiver rather than the service so the
+ * PendingIntent stays a plain explicit broadcast, and the foreground-service start runs inside
+ * the alarm's temporary allowlist window.
+ */
+class GeofenceHeartbeatReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ val serviceIntent = Intent(context, LocationForegroundService::class.java).apply {
+ action = LocationForegroundService.ACTION_GEOFENCE_HEARTBEAT
+ }
+ try {
+ context.startForegroundService(serviceIntent)
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to deliver geofence heartbeat", e)
+ }
+ }
+
+ companion object {
+ private const val TAG = "GeofenceHeartbeat"
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/GeofenceHeartbeatScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/service/GeofenceHeartbeatScheduler.kt
new file mode 100644
index 00000000..7b597978
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/GeofenceHeartbeatScheduler.kt
@@ -0,0 +1,27 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.content.Context
+import com.Colota.util.AlarmScheduler
+
+/**
+ * Wakes [LocationForegroundService] for the geofence-zone heartbeat. Delivered via
+ * [GeofenceHeartbeatReceiver] so the PendingIntent stays a plain explicit broadcast and the
+ * foreground-service start runs inside the alarm's temporary allowlist window.
+ */
+object GeofenceHeartbeatScheduler {
+
+ private val alarm = AlarmScheduler(
+ tag = "GeofenceHeartbeat",
+ requestCode = 9302,
+ receiver = GeofenceHeartbeatReceiver::class.java
+ )
+
+ fun schedule(context: Context, delayMs: Long) = alarm.schedule(context, delayMs)
+
+ fun cancel(context: Context) = alarm.cancel(context)
+}
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 e43f441c..c764e396 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
@@ -110,7 +110,7 @@ class LocationForegroundService : Service() {
@Volatile private var currentZoneGeofence: GeofenceHelper.Geofence? = null
@Volatile private var pendingPauseZone: GeofenceHelper.Geofence? = null
@Volatile private var entryDelayJob: Job? = null
- @Volatile private var heartbeatJob: Job? = null
+ @Volatile private var heartbeatArmed = false
@Volatile private var stationaryHeartbeatArmed = false
// WiFi pause sub-state (same Main-only mutation contract as above)
@@ -178,6 +178,8 @@ class LocationForegroundService : Service() {
const val ACTION_DEBUG_FORCE_MOTION = "com.Colota.DEBUG_FORCE_MOTION"
/** Alarm delivery for the stationary-profile heartbeat; see [StationaryHeartbeatScheduler]. */
const val ACTION_STATIONARY_HEARTBEAT = "com.Colota.STATIONARY_HEARTBEAT"
+ /** Alarm delivery for the geofence-zone heartbeat; see [GeofenceHeartbeatScheduler]. */
+ const val ACTION_GEOFENCE_HEARTBEAT = "com.Colota.GEOFENCE_HEARTBEAT"
/** Actions that skip config reload and preserve current notification state. */
private val LIGHTWEIGHT_ACTIONS = setOf(
@@ -186,7 +188,8 @@ class LocationForegroundService : Service() {
ACTION_REFRESH_NOTIFICATION,
ACTION_RECHECK_PROFILES,
ACTION_STOP_REQUEST,
- ACTION_STATIONARY_HEARTBEAT
+ ACTION_STATIONARY_HEARTBEAT,
+ ACTION_GEOFENCE_HEARTBEAT
)
/**
@@ -282,8 +285,9 @@ class LocationForegroundService : Service() {
loadConfigFromIntent(null)
}
- // Restore pause zone state so a restart without a cached location fix doesn't incorrectly resume tracking
- if (!insidePauseZone) {
+ // Restore pause zone state so a restart without a cached location fix doesn't incorrectly resume tracking.
+ // An explicit start is trusted over the flag, which the bridge writes after starting us.
+ if (!insidePauseZone && (shouldBeTracking || !isLightweight)) {
val savedZone = savedSettings[SettingsKeys.PAUSE_ZONE_NAME]
if (!savedZone.isNullOrBlank()) {
insidePauseZone = true
@@ -304,7 +308,8 @@ class LocationForegroundService : Service() {
restoredGeofence,
savedSettings[SettingsKeys.PAUSE_ZONE_MOTIONLESS_ACTIVE]?.toBoolean() == true
)
- if (restoredGeofence?.heartbeatEnabled == true) {
+ // The alarm's own handler records; doing it here too would double-record
+ if (restoredGeofence?.heartbeatEnabled == true && action != ACTION_GEOFENCE_HEARTBEAT) {
startHeartbeat(
restoredGeofence.heartbeatIntervalMinutes,
firstDelayMs = remainingHeartbeatDelay(restoredGeofence.heartbeatIntervalMinutes)
@@ -350,6 +355,7 @@ class LocationForegroundService : Service() {
ACTION_RECHECK_PROFILES -> handleRecheckProfiles()
ACTION_MANUAL_FLUSH -> handleManualFlush()
ACTION_STATIONARY_HEARTBEAT -> handleStationaryHeartbeatFired()
+ ACTION_GEOFENCE_HEARTBEAT -> handleGeofenceHeartbeatFired(shouldBeTracking)
ACTION_STOP_REQUEST -> stopForegroundServiceWithReason(
intent.getStringExtra(EXTRA_STOP_REASON) ?: "Stopped"
)
@@ -826,7 +832,7 @@ class LocationForegroundService : Service() {
// leaves no request behind, and a lightweight action never runs handleStart to make one.
if (!isLocationUpdatesRegistered()) maybeResumeGps()
- if (zone.heartbeatEnabled && (heartbeatJob == null || heartbeatChanged)) {
+ if (zone.heartbeatEnabled && (!heartbeatArmed || heartbeatChanged)) {
val firstDelayMs =
if (heartbeatJustEnabled) 0L else remainingHeartbeatDelay(zone.heartbeatIntervalMinutes)
startHeartbeat(zone.heartbeatIntervalMinutes, firstDelayMs)
@@ -1187,15 +1193,13 @@ class LocationForegroundService : Service() {
* the interval, and recording on every restore would stack duplicates for one stay.
*/
private fun startHeartbeat(intervalMinutes: Int, firstDelayMs: Long) {
- cancelHeartbeat()
+ heartbeatArmed = true
AppLogger.i(TAG, "Heartbeat started: ${intervalMinutes}min interval, first in ${firstDelayMs}ms")
- heartbeatJob = serviceScope?.launch {
- delay(firstDelayMs)
- recordHeartbeatLocation()
- while (isActive) {
- delay(intervalMinutes * 60_000L)
- recordHeartbeatLocation()
- }
+ if (firstDelayMs <= 0L) {
+ serviceScope?.launch { recordHeartbeatLocation() }
+ GeofenceHeartbeatScheduler.schedule(this, intervalMinutes * 60_000L)
+ } else {
+ GeofenceHeartbeatScheduler.schedule(this, firstDelayMs)
}
}
@@ -1211,10 +1215,52 @@ class LocationForegroundService : Service() {
}
private fun cancelHeartbeat() {
- if (heartbeatJob == null) return
- heartbeatJob?.cancel()
- heartbeatJob = null
- AppLogger.i(TAG, "Heartbeat cancelled")
+ // Unconditional: a fresh instance reads as unarmed, but the old process's alarm still fires
+ val wasArmed = heartbeatArmed
+ heartbeatArmed = false
+ GeofenceHeartbeatScheduler.cancel(this)
+ if (wasArmed) AppLogger.i(TAG, "Heartbeat cancelled")
+ }
+
+ /** The stored timestamp decides whether to record, since a restore may already have done it. */
+ private fun handleGeofenceHeartbeatFired(shouldBeTracking: Boolean) {
+ val zone = currentZoneGeofence
+ if (!insidePauseZone || zone?.heartbeatEnabled != true) {
+ cancelHeartbeat()
+ // A zone-to-zone move leaves the old alarm pending, so this reaches healthy services
+ // too. A pause hold also has no stream, so only intent may stop one.
+ if (!shouldBeTracking) stopSelf()
+ else if (!isLocationUpdatesRegistered()) maybeResumeGps()
+ return
+ }
+ heartbeatArmed = true
+
+ val remaining = remainingHeartbeatDelay(zone.heartbeatIntervalMinutes)
+ if (remaining > 0L) {
+ GeofenceHeartbeatScheduler.schedule(this, remaining)
+ return
+ }
+
+ // The alarm's wake window ends when onReceive returns, and a foreground service does not
+ // hold the CPU, so the DB write and send need their own wakelock.
+ val wakeLock = acquireHeartbeatWakeLock()
+ val scope = serviceScope
+ if (scope == null) {
+ if (wakeLock?.isHeld == true) wakeLock.release()
+ return
+ }
+ scope.launch {
+ try {
+ recordHeartbeatLocation()
+ } finally {
+ if (wakeLock?.isHeld == true) wakeLock.release()
+ }
+ }
+ GeofenceHeartbeatScheduler.schedule(this, zone.heartbeatIntervalMinutes * 60_000L)
+
+ // A lightweight action builds no stream, and zone exit is only seen on one. Last, because
+ // the recheck it triggers can exit the zone synchronously and cancel the alarm just armed.
+ if (!isLocationUpdatesRegistered()) maybeResumeGps()
}
/**
@@ -1544,7 +1590,7 @@ class LocationForegroundService : Service() {
private fun acquireHeartbeatWakeLock(): PowerManager.WakeLock? {
val pm = getSystemService(POWER_SERVICE) as? PowerManager ?: return null
- return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "colota:stationary-heartbeat").apply {
+ return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "colota:heartbeat").apply {
acquire(HEARTBEAT_WAKELOCK_TIMEOUT_MS)
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/StationaryHeartbeatScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/service/StationaryHeartbeatScheduler.kt
index f58fe08d..bd3310ca 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/StationaryHeartbeatScheduler.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/StationaryHeartbeatScheduler.kt
@@ -5,51 +5,23 @@
package com.Colota.service
-import android.app.AlarmManager
-import android.app.PendingIntent
import android.content.Context
-import android.content.Intent
-import com.Colota.util.AppLogger
+import com.Colota.util.AlarmScheduler
/**
- * Schedules the stationary-profile heartbeat alarm. Uses setAndAllowWhileIdle (like
- * AutoExportScheduler) so it fires through Doze without the SCHEDULE_EXACT_ALARM permission;
- * the OS floors it to ~9min while idle, which suits a stationary cadence. Delivered to
- * [StationaryHeartbeatReceiver], which forwards it to [LocationForegroundService].
+ * Wakes [LocationForegroundService] for the stationary-profile heartbeat. Delivered via
+ * [StationaryHeartbeatReceiver] so the PendingIntent stays a plain explicit broadcast and the
+ * foreground-service start runs inside the alarm's temporary allowlist window.
*/
object StationaryHeartbeatScheduler {
- private const val TAG = "StationaryHeartbeat"
- private const val REQUEST_CODE = 9301
- /** Cadence floor; Doze also floors allow-while-idle to ~9min. */
- private const val MIN_INTERVAL_MS = 60_000L
+ private val alarm = AlarmScheduler(
+ tag = "StationaryHeartbeat",
+ requestCode = 9301,
+ receiver = StationaryHeartbeatReceiver::class.java
+ )
- fun schedule(context: Context, intervalMs: Long) {
- val am = context.getSystemService(AlarmManager::class.java) ?: return
- val delay = maxOf(intervalMs, MIN_INTERVAL_MS)
- am.setAndAllowWhileIdle(
- AlarmManager.RTC_WAKEUP,
- System.currentTimeMillis() + delay,
- pendingIntent(context)
- )
- AppLogger.d(TAG, "Stationary heartbeat armed: ${delay / 1000}s")
- }
+ fun schedule(context: Context, intervalMs: Long) = alarm.schedule(context, intervalMs)
- fun cancel(context: Context) {
- val am = context.getSystemService(AlarmManager::class.java) ?: return
- am.cancel(pendingIntent(context))
- AppLogger.d(TAG, "Stationary heartbeat cancelled")
- }
-
- private fun pendingIntent(context: Context): PendingIntent {
- val intent = Intent(context, StationaryHeartbeatReceiver::class.java).apply {
- setPackage(context.packageName)
- }
- return PendingIntent.getBroadcast(
- context,
- REQUEST_CODE,
- intent,
- PendingIntent.FLAG_IMMUTABLE
- )
- }
+ fun cancel(context: Context) = alarm.cancel(context)
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/AlarmScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/util/AlarmScheduler.kt
new file mode 100644
index 00000000..7817ac18
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/AlarmScheduler.kt
@@ -0,0 +1,60 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.util
+
+import android.app.AlarmManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+
+/**
+ * One-shot wake-up alarm delivered to [receiver], re-armed by whoever handles it.
+ *
+ * setAndAllowWhileIdle fires through Doze without SCHEDULE_EXACT_ALARM, at the cost of being
+ * inexact: the platform adds a delivery window of roughly 75% of the requested delay, so callers
+ * must treat it as a minimum. Exact delivery would need a permission restricted to timer apps.
+ */
+internal class AlarmScheduler(
+ private val tag: String,
+ private val requestCode: Int,
+ private val receiver: Class<out BroadcastReceiver>
+) {
+
+ fun schedule(context: Context, delayMs: Long) {
+ val am = context.getSystemService(AlarmManager::class.java) ?: return
+ val delay = maxOf(delayMs, MIN_INTERVAL_MS)
+ am.setAndAllowWhileIdle(
+ AlarmManager.RTC_WAKEUP,
+ System.currentTimeMillis() + delay,
+ pendingIntent(context)
+ )
+ AppLogger.d(tag, "Alarm armed: ${delay / 1000}s")
+ }
+
+ fun cancel(context: Context) {
+ val am = context.getSystemService(AlarmManager::class.java) ?: return
+ am.cancel(pendingIntent(context))
+ AppLogger.d(tag, "Alarm cancelled")
+ }
+
+ private fun pendingIntent(context: Context): PendingIntent {
+ val intent = Intent(context, receiver).apply {
+ setPackage(context.packageName)
+ }
+ return PendingIntent.getBroadcast(
+ context,
+ requestCode,
+ intent,
+ PendingIntent.FLAG_IMMUTABLE
+ )
+ }
+
+ private companion object {
+ /** Cadence floor. The inexact delivery window stretches the real interval well past this. */
+ const val MIN_INTERVAL_MS = 60_000L
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/GeofenceHeartbeatSchedulerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/GeofenceHeartbeatSchedulerTest.kt
new file mode 100644
index 00000000..594b7231
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/GeofenceHeartbeatSchedulerTest.kt
@@ -0,0 +1,65 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.app.AlarmManager
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.Colota.util.AppLogger
+import io.mockk.*
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+
+@RunWith(RobolectricTestRunner::class)
+class GeofenceHeartbeatSchedulerTest {
+
+ private lateinit var context: Context
+ private lateinit var alarmManager: AlarmManager
+
+ @Before
+ fun setUp() {
+ context = ApplicationProvider.getApplicationContext()
+ alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+
+ mockkObject(AppLogger)
+ every { AppLogger.d(any(), any()) } just Runs
+ every { AppLogger.i(any(), any()) } just Runs
+ every { AppLogger.w(any(), any()) } just Runs
+ every { AppLogger.e(any(), any()) } just Runs
+
+ GeofenceHeartbeatScheduler.cancel(context)
+ StationaryHeartbeatScheduler.cancel(context)
+ }
+
+ @After
+ fun tearDown() {
+ unmockkObject(AppLogger)
+ }
+
+ @Test
+ fun `re-arming replaces the pending alarm instead of stacking`() {
+ // startHeartbeat no longer cancels first, so correctness relies on the same request code
+ GeofenceHeartbeatScheduler.schedule(context, 900_000L)
+ GeofenceHeartbeatScheduler.schedule(context, 900_000L)
+
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+ }
+
+ @Test
+ fun `cancelling one heartbeat leaves the other armed`() {
+ StationaryHeartbeatScheduler.schedule(context, 600_000L)
+ GeofenceHeartbeatScheduler.schedule(context, 900_000L)
+
+ GeofenceHeartbeatScheduler.cancel(context)
+
+ assertEquals(1, shadowOf(alarmManager).scheduledAlarms.size)
+ }
+}
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 a01ea98b..631212a7 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
@@ -108,6 +108,9 @@ class LocationForegroundServiceTest {
every { LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true
mockkObject(BatteryRecoveryScheduler)
+ mockkObject(GeofenceHeartbeatScheduler)
+ every { GeofenceHeartbeatScheduler.schedule(any(), any()) } just Runs
+ every { GeofenceHeartbeatScheduler.cancel(any()) } just Runs
every { BatteryRecoveryScheduler.schedule(any()) } just Runs
every { BatteryRecoveryScheduler.cancel(any()) } just Runs
@@ -131,6 +134,7 @@ class LocationForegroundServiceTest {
unmockkObject(PayloadBuilder)
unmockkObject(AppLogger)
unmockkObject(BatteryRecoveryScheduler)
+ unmockkObject(GeofenceHeartbeatScheduler)
unmockkStatic(android.os.Looper::class)
}
@@ -2946,6 +2950,7 @@ class LocationForegroundServiceTest {
advanceTimeBy(1_000)
verify(exactly = 1) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ verify { GeofenceHeartbeatScheduler.schedule(any(), 15 * 60_000L) }
}
@Test
@@ -2984,6 +2989,7 @@ class LocationForegroundServiceTest {
advanceTimeBy(1_000)
verify(exactly = 1) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ verify { GeofenceHeartbeatScheduler.schedule(any(), 15 * 60_000L) }
}
@Test
@@ -3015,19 +3021,116 @@ class LocationForegroundServiceTest {
}
@Test
- fun `startHeartbeat waits a full interval when restoring a zone`() = runServiceTest {
- // Every service restart restores the zone. Recording here would add a duplicate point,
- // and POST one, for a stay the previous instance already covered.
+ fun `restoring arms for the time left on the interval, not a fresh one`() = runServiceTest {
+ // Restarting the clock would starve a device that respawns more often than the interval
every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
setField("currentZoneGeofence", homeGeofence)
- invokeStartHeartbeat(15, firstDelayMs = 15 * 60_000L)
+ invokeStartHeartbeat(15, firstDelayMs = 5 * 60_000L)
advanceTimeBy(1_000)
verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ verify { GeofenceHeartbeatScheduler.schedule(any(), 5 * 60_000L) }
+ }
+
+ @Test
+ fun `a fired heartbeat re-registers a location stream the cold start never made`() = runServiceTest {
+ // Zone exit is only ever seen on the stream, so without this the alarm keeps recording at a
+ // zone the user already left
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+ every { dbHelper.getSetting(SettingsKeys.HEARTBEAT_LAST_AT) } returns
+ (System.currentTimeMillis() - 20 * 60_000L).toString()
+ setField("insidePauseZone", true)
+ setField("currentZoneName", "Home")
+ setField("currentZoneGeofence", geofence("Home", heartbeatEnabled = true))
+ setField("locationUpdateCallback", null)
+
+ invokeGeofenceHeartbeatFired()
+
+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `a fired heartbeat records and re-arms for the next interval`() = runServiceTest {
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+ every { dbHelper.getSetting(SettingsKeys.HEARTBEAT_LAST_AT) } returns
+ (System.currentTimeMillis() - 20 * 60_000L).toString()
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", geofence("Home", heartbeatEnabled = true))
+
+ invokeGeofenceHeartbeatFired()
+ advanceTimeBy(1_000)
- advanceTimeBy(15 * 60_000L)
verify(exactly = 1) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ verify { GeofenceHeartbeatScheduler.schedule(any(), 15 * 60_000L) }
+ }
+
+ @Test
+ fun `a fired heartbeat does not duplicate the point a restore just recorded`() = runServiceTest {
+ // A cold service restores the zone and records in onStartCommand before this action runs
+ every { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 1L
+ every { dbHelper.getSetting(SettingsKeys.HEARTBEAT_LAST_AT) } returns
+ System.currentTimeMillis().toString()
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", geofence("Home", heartbeatEnabled = true))
+
+ invokeGeofenceHeartbeatFired()
+ advanceTimeBy(1_000)
+
+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
+ verify { GeofenceHeartbeatScheduler.schedule(any(), match { it > 14 * 60_000L }) }
+ }
+
+ @Test
+ fun `cancelling clears an alarm a previous process left pending`() = runServiceTest {
+ // A fresh instance reads as unarmed, but the alarm outlives the process that set it
+ setField("heartbeatArmed", false)
+
+ invokeCancelHeartbeat()
+
+ verify { GeofenceHeartbeatScheduler.cancel(any()) }
+ }
+
+ @Test
+ fun `a stale heartbeat stops a service the user already stopped`() = runServiceTest {
+ setField("heartbeatArmed", true)
+ setField("insidePauseZone", false)
+ setField("currentZoneGeofence", null)
+
+ invokeGeofenceHeartbeatFired(shouldBeTracking = false)
+
+ verify { GeofenceHeartbeatScheduler.cancel(any()) }
+ // startForeground already ran, so without this a dead service keeps its notification
+ verify { service.stopSelf() }
+ }
+
+ @Test
+ fun `a bail-out repairs the stream when no hold explains its absence`() = runServiceTest {
+ // A latched zone with no geofence and no stream would otherwise never recover
+ setField("heartbeatArmed", true)
+ setField("insidePauseZone", true)
+ setField("currentZoneGeofence", null)
+ setField("locationUpdateCallback", null)
+
+ invokeGeofenceHeartbeatFired(shouldBeTracking = true)
+
+ verify(exactly = 0) { service.stopSelf() }
+ verify { locationProvider.requestLocationUpdates(any(), any(), any(), any()) }
+ }
+
+ @Test
+ fun `an old zone's heartbeat never stops a service the user still wants`() = runServiceTest {
+ // A wifi hold makes a healthy paused service look streamless
+ setField("heartbeatArmed", true)
+ setField("insidePauseZone", true)
+ setField("isWifiPaused", true)
+ setField("currentZoneGeofence", geofence("Neighbourhood", heartbeatEnabled = false))
+
+ invokeGeofenceHeartbeatFired(shouldBeTracking = true)
+
+ verify { GeofenceHeartbeatScheduler.cancel(any()) }
+ verify(exactly = 0) { service.stopSelf() }
+ verify(exactly = 0) { dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) }
}
@@ -3116,6 +3219,20 @@ class LocationForegroundServiceTest {
method.invoke(service, intervalMinutes, firstDelayMs)
}
+ private fun invokeCancelHeartbeat() {
+ val method = LocationForegroundService::class.java.getDeclaredMethod("cancelHeartbeat")
+ method.isAccessible = true
+ method.invoke(service)
+ }
+
+ private fun invokeGeofenceHeartbeatFired(shouldBeTracking: Boolean = true) {
+ val method = LocationForegroundService::class.java.getDeclaredMethod(
+ "handleGeofenceHeartbeatFired", Boolean::class.java
+ )
+ method.isAccessible = true
+ method.invoke(service, shouldBeTracking)
+ }
+
private fun invokeRecordHeartbeatLocation() = runBlocking {
val method = LocationForegroundService::class.java.getDeclaredMethod(
"recordHeartbeatLocation", kotlin.coroutines.Continuation::class.java
diff --git a/fastlane/metadata/android/en-US/changelogs/46.txt b/fastlane/metadata/android/en-US/changelogs/46.txt
index 046ab9d9..9e29f54d 100644
--- a/fastlane/metadata/android/en-US/changelogs/46.txt
+++ b/fastlane/metadata/android/en-US/changelogs/46.txt
@@ -1,2 +1,3 @@
- Map requests identify the app by name and version, never the device or user
- Tracking no longer refuses to start when notifications are turned off
+- Geofence heartbeat keeps recording while the phone sleeps