Colota - Android GPS Location tracker
fix(service): stop a destroyed service instance leaking location updates (#547)
Max Dietrichdde5ed90331b
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.ktindex c1b248ca..4f2f9a92 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@@ -239,7 +239,7 @@ class LocationForegroundService : Service() {}private fun unregisterLocationProvidersReceiver() {- unregisterReceiver(locationProvidersReceiver)+ try { unregisterReceiver(locationProvidersReceiver) } catch (_: IllegalArgumentException) {}}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {@@ -397,27 +397,23 @@ class LocationForegroundService : Service() {override fun onDestroy() {AppLogger.d(TAG, "Service destroyed")- // Teardown DB writes throw during a restore; swallow so the throw can't- // bubble out of onDestroy and kill the process. State is overwritten by the swap.- try {- motionDetector?.stop()+ // Isolated per step: a skipped stopLocationUpdates leaves this instance receiving fixes+ // the cancelled scope below can no longer save.+ teardownStep("motionDetector") { motionDetector?.stop() }+ teardownStep("entryDelay") {entryDelayJob?.cancel()entryDelayJob = nullpendingPauseZone = null- unregisterWifiPause()- cancelHeartbeat()- unregisterLocationProvidersReceiver()- unregisterDebugMotionReceiver()- batteryMonitor.stop()- conditionMonitor.stop()- stopLocationUpdates()- syncManager.stopPeriodicSync()- networkManager.destroy()- } catch (e: IllegalStateException) {- AppLogger.w(TAG, "Teardown step skipped: ${e.message}")- } catch (e: Exception) {- AppLogger.e(TAG, "Unexpected error during service teardown", e)}+ teardownStep("wifiPause") { unregisterWifiPause() }+ teardownStep("heartbeat") { cancelHeartbeat() }+ teardownStep("locationProvidersReceiver") { unregisterLocationProvidersReceiver() }+ teardownStep("debugMotionReceiver") { unregisterDebugMotionReceiver() }+ teardownStep("batteryMonitor") { batteryMonitor.stop() }+ teardownStep("conditionMonitor") { conditionMonitor.stop() }+ teardownStep("locationUpdates") { stopLocationUpdates() }+ teardownStep("periodicSync") { syncManager.stopPeriodicSync() }+ teardownStep("networkManager") { networkManager.destroy() }// Critical teardown: must run so pauseAllDbWriters' poll loop sees isRunning=false.serviceScope?.cancel()@@ -428,13 +424,35 @@ class LocationForegroundService : Service() {super.onDestroy()}+ /** Teardown DB writes throw during a restore; the state is overwritten by the swap anyway. */+ private fun teardownStep(name: String, block: () -> Unit) {+ try {+ block()+ } catch (e: IllegalStateException) {+ AppLogger.w(TAG, "Teardown step '$name' skipped: ${e.message}")+ } catch (e: Exception) {+ AppLogger.e(TAG, "Unexpected error during teardown step '$name'", e)+ }+ }+override fun onBind(intent: Intent?): IBinder? = nullprivate fun setupLocationUpdates() {if (isWifiPaused || isMotionlessPaused) return // GPS intentionally stopped by a zone pause hold+ // The resume paths reach here without a stop, and the assignment below would orphan the old+ // callback with no reference left to unregister it.+ locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }+val callback = object : LocationUpdateCallback {override fun onLocationUpdate(location: Location) {+ // Only onDestroy nulls the scope, so this instance is dead and the OS is still+ // feeding it - every fix below would be discarded silently.+ if (serviceScope == null) {+ AppLogger.e(TAG, "Location received after destroy - removing leaked location updates")+ locationProvider.removeLocationUpdates(this)+ return+ }lastFixAtMs = SystemClock.elapsedRealtime()handleLocationUpdate(location)}@@ -530,13 +548,7 @@ class LocationForegroundService : Service() {delay(TRACKING_HEARTBEAT_INTERVAL_MS)// Catch here so a DB or system-service hiccup doesn't kill the heartbeat loop.try {- val state = when {- locationUpdateCallback == null -> "STOPPED"- isWifiPaused && isMotionlessPaused -> "PAUSED(wifi+motionless)"- isWifiPaused -> "PAUSED(wifi)"- isMotionlessPaused -> "PAUSED(motionless)"- else -> "ACTIVE"- }+ val state = trackingStateLabel()val sinceLastFix = SystemClock.elapsedRealtime() - lastFixAtMsval (battery, _) = deviceInfoHelper.getCachedBatteryStatus()val doze = (getSystemService(POWER_SERVICE) as? PowerManager)?.isDeviceIdleMode ?: false@@ -552,6 +564,17 @@ class LocationForegroundService : Service() {}}+ /** Wifi and motionless are holds inside a zone pause, so they're checked first. Without+ * PAUSED(zone) a latched pause reads as ACTIVE in an exported log. */+ private fun trackingStateLabel(): String = when {+ locationUpdateCallback == null -> "STOPPED"+ isWifiPaused && isMotionlessPaused -> "PAUSED(wifi+motionless)"+ isWifiPaused -> "PAUSED(wifi)"+ isMotionlessPaused -> "PAUSED(motionless)"+ insidePauseZone -> "PAUSED(zone)"+ else -> "ACTIVE"+ }+private fun cancelTrackingHeartbeatLogger() {trackingHeartbeatJob?.cancel()trackingHeartbeatJob = nulldiff --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.ktindex 79ef776e..f71aacae 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@@ -1827,6 +1827,92 @@ class LocationForegroundServiceTest {assertEquals("syncManager.stop", order[2])}+ // =========================================================================+ // Destroyed instance must not keep receiving fixes+ // =========================================================================++ @Test+ fun `onDestroy removes location updates even when an earlier teardown step throws`() {+ val callback = mockk<LocationUpdateCallback>(relaxed = true)+ setField("locationUpdateCallback", callback)+ every { conditionMonitor.stop() } throws IllegalStateException("db closed during restore")++ invokeOnDestroy()++ // The scope is cancelled either way, so a skipped unregister leaves a dead instance+ // receiving fixes it can no longer save.+ verify { locationProvider.removeLocationUpdates(callback) }+ verify { syncManager.stopPeriodicSync() }+ assertNull(getField<CoroutineScope?>("serviceScope"))+ }++ @Test+ fun `onDestroy removes location updates when the providers receiver was never registered`() {+ val callback = mockk<LocationUpdateCallback>(relaxed = true)+ setField("locationUpdateCallback", callback)+ every { service.unregisterReceiver(any()) } throws IllegalArgumentException("Receiver not registered")++ invokeOnDestroy()++ verify { locationProvider.removeLocationUpdates(callback) }+ }++ @Test+ fun `location callback sheds its registration once the service scope is gone`() {+ val registered = slot<LocationUpdateCallback>()+ every { locationProvider.requestLocationUpdates(any(), any(), any(), capture(registered)) } just Runs+ invokeSetupLocationUpdates()+ setField("serviceScope", null)++ registered.captured.onLocationUpdate(mockLocation())++ // A dead instance can't persist anything, so it must let go instead of holding GNSS open.+ verify { locationProvider.removeLocationUpdates(registered.captured) }+ verify(exactly = 0) {+ dbHelper.saveLocation(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())+ }+ }++ @Test+ fun `setupLocationUpdates drops the previous registration before replacing it`() {+ val orphan = mockk<LocationUpdateCallback>(relaxed = true)+ setField("locationUpdateCallback", orphan)++ invokeSetupLocationUpdates()++ // Without this the old callback is orphaned and nothing can unregister it again.+ verify { locationProvider.removeLocationUpdates(orphan) }+ }++ // =========================================================================+ // trackingStateLabel - heartbeat diagnostics+ // =========================================================================++ @Test+ fun `trackingStateLabel reports a zone pause instead of ACTIVE`() {+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))+ setField("insidePauseZone", true)++ // ACTIVE here leaves an exported log ambiguous about whether the zone is still latched.+ assertEquals("PAUSED(zone)", invokeTrackingStateLabel())+ }++ @Test+ fun `trackingStateLabel reports the wifi hold ahead of the zone pause`() {+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))+ setField("insidePauseZone", true)+ setField("isWifiPaused", true)++ assertEquals("PAUSED(wifi)", invokeTrackingStateLabel())+ }++ @Test+ fun `trackingStateLabel reports ACTIVE while tracking outside every zone`() {+ setField("locationUpdateCallback", mockk<LocationUpdateCallback>(relaxed = true))++ assertEquals("ACTIVE", invokeTrackingStateLabel())+ }+// =========================================================================// stopForegroundServiceWithReason - battery critical path// =========================================================================@@ -2311,6 +2397,12 @@ class LocationForegroundServiceTest {method.invoke(service, interval, distance, syncInterval)}+ private fun invokeTrackingStateLabel(): String {+ val method = LocationForegroundService::class.java.getDeclaredMethod("trackingStateLabel")+ method.isAccessible = true+ return method.invoke(service) as String+ }+private fun invokeOnDestroy() {val method = LocationForegroundService::class.java.getDeclaredMethod("onDestroy")method.isAccessible = truediff --git a/fastlane/metadata/android/en-US/changelogs/43.txt b/fastlane/metadata/android/en-US/changelogs/43.txtindex 107238ef..faec1833 100644--- a/fastlane/metadata/android/en-US/changelogs/43.txt+++ b/fastlane/metadata/android/en-US/changelogs/43.txt@@ -3,3 +3,4 @@- FOSS: more reliable GPS on Android 12+ and a crash fix on GPS-less devices- Fixed a paused geofence wrongly resuming after a restart- Fixed the Stationary profile getting stuck active while still driving+- Fixed tracking silently stopping after restoring a backup