Colota - Android GPS Location tracker
fix: resolve race condition in profile switching that stops tracking
Max Dietrich0035a2ad5746
diff --git a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.ktindex e43b3996..88c24695 100644--- a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt+++ b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt@@ -14,26 +14,24 @@ import android.os.Bundleimport android.os.Looper/**- * Location provider backed by Android's native LocationManager.- * Used in the FOSS product flavor (F-Droid distribution, no Google Play Services).- * Registers both GPS_PROVIDER and NETWORK_PROVIDER for faster fixes — GPS is- * primary but network provides a quick initial position (similar to FusedLocationProvider).+ * LocationManager-based provider for FOSS flavor (no Google Play Services).+ * Uses GPS as primary source with NETWORK_PROVIDER as coarse fallback.*/@SuppressLint("MissingPermission")class NativeLocationProvider(context: Context) : LocationProvider {companion object {- /** Suppress network updates for this duration after the last GPS fix. */+ /** Ignore network updates for this long after the last GPS fix. */private const val GPS_SUPPRESSION_MS = 10_000L}private val locationManager: LocationManager =context.getSystemService(Context.LOCATION_SERVICE) as LocationManager- /** Maps each callback to its GPS listener and optional network listener. */+ /** Maps callback -> [GPS listener, network listener?]. */private val listenerMap = java.util.concurrent.ConcurrentHashMap<LocationUpdateCallback, List<LocationListener>>()- /** Timestamp of last GPS fix, used to suppress redundant network updates. */+ /** Last GPS fix time; suppresses redundant network updates. */@Volatile private var lastGpsTime: Long = 0override fun requestLocationUpdates(@@ -64,8 +62,7 @@ class NativeLocationProvider(context: Context) : LocationProvider {looper)- // Also register NETWORK_PROVIDER for faster initial fix (WiFi/cell).- // GPS remains primary for accuracy; network provides coarse fallback.+ // NETWORK_PROVIDER as coarse fallback for faster initial fixif (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {val networkListener = object : LocationListener {override fun onLocationChanged(location: Location) {@@ -88,7 +85,6 @@ class NativeLocationProvider(context: Context) : LocationProvider {)}} catch (e: SecurityException) {- // Clean up any listeners that were registered before the errorlisteners.forEach { locationManager.removeUpdates(it) }throw e}diff --git a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.ktindex 3202702e..f943a42c 100644--- a/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt+++ b/apps/mobile/android/app/src/gms/java/com/Colota/location/GmsLocationProvider.kt@@ -10,10 +10,7 @@ import android.location.Locationimport android.os.Looperimport com.google.android.gms.location.*-/**- * Location provider backed by Google Play Services FusedLocationProviderClient.- * Used in the GMS product flavor (Google Play distribution).- */+/** FusedLocationProviderClient-based provider for GMS flavor. */class GmsLocationProvider(context: Context) : LocationProvider {private val fusedClient: FusedLocationProviderClient =@@ -34,10 +31,9 @@ class GmsLocationProvider(context: Context) : LocationProvider {}callbackMap[callback] = gmsCallback- val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMs * 2)+ val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMs).setMinUpdateIntervalMillis(intervalMs).setMinUpdateDistanceMeters(minDistanceMeters)- .setMaxUpdateDelayMillis(intervalMs * 2).build()try {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 99572c49..afbbb5f3 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@@ -25,9 +25,7 @@ import com.Colota.location.LocationUpdateCallbackimport kotlinx.coroutines.*import java.util.Locale-/**- * Foreground Service for continuous background location tracking.- */+/** Foreground service for continuous GPS tracking and location syncing. */class LocationForegroundService : Service() {private lateinit var locationProvider: LocationProvider@@ -46,12 +44,13 @@ class LocationForegroundService : Service() {@Volatile private var serviceScope: CoroutineScope? = null@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null+ @Volatile private var locationRestartJob: Job? = null@Volatile private var insidePauseZone = false@Volatile private var currentZoneName: String? = null@Volatile private var lastKnownLocation: android.location.Location? = null@Volatile private lateinit var config: ServiceConfig- private var fieldMap: Map<String, String>? = null+ @Volatile private var fieldMap: Map<String, String>? = null@Volatile private var customFields: Map<String, String>? = nullcompanion object {@@ -116,12 +115,15 @@ class LocationForegroundService : Service() {val action = intent?.actionval isLightweight = action in LIGHTWEIGHT_ACTIONS- // Only reload config for full starts (not lightweight actions)+ // Skip config reload for lightweight actions, but if the service was+ // killed and restarted by one, load from DB so SyncManager has an endpoint.if (!isLightweight) {loadConfigFromIntent(intent)+ } else if (!::config.isInitialized) {+ loadConfigFromIntent(null)}- // Must call startForeground within 5s — use best available status+ // Must call startForeground within 5sval initialStatus = notificationHelper.getInitialStatus(insidePauseZone, currentZoneName, lastKnownLocation)@@ -154,7 +156,6 @@ class LocationForegroundService : Service() {Log.d(TAG, "Force exit from zone: $currentZoneName")}exitPauseZone()- // Immediately recheck with current locationlastKnownLocation?.let { recheckZoneWithLocation(it) }}return START_STICKY@@ -175,23 +176,24 @@ class LocationForegroundService : Service() {return START_STICKY}else -> {- serviceScope?.launch {- // FusedLocationClient requires Main looper+ locationRestartJob?.cancel()+ locationRestartJob = serviceScope?.launch {withContext(Dispatchers.Main) {stopLocationUpdates()syncManager.stopPeriodicSync()setupLocationUpdates()syncManager.startPeriodicSync()++ // Start after setup so profile evaluations don't race+ // with setupLocationUpdates above+ conditionMonitor.start()}if (config.syncIntervalSeconds == 0 && config.endpoint.isNotBlank()) {syncManager.manualFlush()}}-- // Start condition monitors for profile-based config switching- conditionMonitor.start()}}@@ -241,12 +243,9 @@ class LocationForegroundService : Service() {onSuccess = { location ->location?.let {lastKnownLocation = it-- // Check if starting in a pause zonegeofenceHelper.getPauseZone(it)?.let { zoneName ->enterPauseZone(zoneName)} ?: run {- // Not in zone - show coordinates immediatelyupdateNotification(it.latitude, it.longitude, forceUpdate = true)}}@@ -256,6 +255,9 @@ class LocationForegroundService : Service() {} catch (e: SecurityException) {Log.e(TAG, "Location permission missing", e)stopForegroundServiceWithReason("Location permission missing")+ } catch (e: Exception) {+ Log.e(TAG, "Failed to start location updates", e)+ stopForegroundServiceWithReason("Location provider error")}}@@ -270,18 +272,15 @@ class LocationForegroundService : Service() {val cachedLoc = lastKnownLocationval now = System.currentTimeMillis()- // If we have a fresh location (less than 1 min old), recheck immediately- if (cachedLoc != null && (now - cachedLoc.time) < 60000) {+ if (cachedLoc != null && (now - cachedLoc.time) < 60_000) {recheckZoneWithLocation(cachedLoc)} else {- // Otherwise, request the last known location from the providerlocationProvider.getLastLocation(onSuccess = { location ->if (location != null) {lastKnownLocation = locationrecheckZoneWithLocation(location)} else {- // No location available - if in zone, exit itif (insidePauseZone) {if (BuildConfig.DEBUG) {Log.d(TAG, "No location for recheck, forcing exit from zone")@@ -292,7 +291,6 @@ class LocationForegroundService : Service() {},onFailure = { e ->Log.e(TAG, "Recheck error", e)- // On error, also exit zone if in oneif (insidePauseZone) {exitPauseZone()}@@ -306,17 +304,13 @@ class LocationForegroundService : Service() {val zoneName = geofenceHelper.getPauseZone(location)when {- // Just entered a pause zone or changed zoneszoneName != null && (!insidePauseZone || zoneName != currentZoneName) -> {enterPauseZone(zoneName)}-- // Just exited pause zonezoneName == null && insidePauseZone -> {exitPauseZone()}-- // Still in the same pause zone - update coords but keep paused status+ // Same zone - refresh notification coordszoneName != null && insidePauseZone && zoneName == currentZoneName -> {updateNotification(lat = location.latitude,@@ -327,7 +321,6 @@ class LocationForegroundService : Service() {)}- // Standard movement (no zone) - show coordselse -> {updateNotification(location.latitude,@@ -338,11 +331,7 @@ class LocationForegroundService : Service() {}}- /**- * Calculates speed from consecutive GPS points when the device doesn't- * provide it natively. Sets speed on the Location object via setSpeed(),- * which also causes hasSpeed() to return true for all downstream consumers.- */+ /** Derives speed from consecutive GPS points when the device doesn't report it. */private fun applySpeedFallback(location: android.location.Location) {if (location.hasSpeed()) return@@ -364,10 +353,17 @@ class LocationForegroundService : Service() {return}+ // Deduplicate: FLP can redeliver the same fix to a newly registered listener+ val prev = lastKnownLocation+ if (prev != null && location.time == prev.time+ && location.latitude == prev.latitude+ && location.longitude == prev.longitude) {+ return+ }+applySpeedFallback(location)- // Feed location to profile manager for speed-based condition evaluation- // (after accuracy filter so bad GPS data doesn't pollute speed average)+ // After accuracy filter so bad GPS doesn't pollute speed averageprofileManager.onLocationUpdate(location)lastKnownLocation = location@@ -395,7 +391,6 @@ class LocationForegroundService : Service() {val timestampSec = location.time / 1000val currentFieldMap = fieldMap ?: emptyMap()- // DB + network on IO thread; notification dispatches back to MainserviceScope?.launch {val locationId = dbHelper.saveLocation(latitude = location.latitude,@@ -462,9 +457,6 @@ class LocationForegroundService : Service() {if (BuildConfig.DEBUG) Log.d(TAG, "Exited pause zone: $exited")}- /**- * Thin wrapper that delegates to NotificationHelper with current service state.- */private fun updateNotification(lat: Double? = null,lon: Double? = null,@@ -492,7 +484,7 @@ class LocationForegroundService : Service() {Log.i(TAG, "Stopping: $reason")}- // Clear active profile so JS UI resets the profile indicator+ // Reset profile indicator in JS UIif (profileManager.getActiveProfileName() != null) {LocationServiceModule.sendProfileSwitchEvent(null, null)}@@ -512,14 +504,11 @@ class LocationForegroundService : Service() {notificationHelper.buildStoppedNotification(reason))- locationUpdateCallback?.let { locationProvider.removeLocationUpdates(it) }+ stopLocationUpdates()stopSelf()}- /**- * Dynamically switches GPS interval and sync config when a profile activates/deactivates.- * No full service restart — just re-requests location updates with new parameters.- */+ /** Hot-swaps GPS interval and sync config on profile change. */private fun applyProfileConfig(interval: Long, distance: Float, syncInterval: Int) {config = config.copy(interval = interval,@@ -527,40 +516,24 @@ class LocationForegroundService : Service() {syncIntervalSeconds = syncInterval)- syncManager.updateConfig(- endpoint = config.endpoint,- syncIntervalSeconds = syncInterval,- retryIntervalSeconds = config.retryIntervalSeconds,- maxRetries = config.maxRetries,- isOfflineMode = config.isOfflineMode,- isWifiOnlySync = config.isWifiOnlySync,- authHeaders = secureStorage.getAuthHeaders(),- httpMethod = config.httpMethod- )+ pushConfigToSyncManager()- serviceScope?.launch {- withContext(Dispatchers.Main) {- stopLocationUpdates()- setupLocationUpdates()- }- }+ // Synchronous restart on Main thread to avoid duplicate locations from+ // the old listener firing during an async coroutine window.+ locationRestartJob?.cancel()+ locationRestartJob = null+ stopLocationUpdates()+ setupLocationUpdates()- // Update notification to show/hide profile name in titleval loc = lastKnownLocationupdateNotification(lat = loc?.latitude, lon = loc?.longitude, forceUpdate = true)if (BuildConfig.DEBUG) {- Log.i(TAG, "Profile config applied: ${profileManager.getActiveProfileName() ?: "default"} — interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")+ Log.i(TAG, "Profile config applied: ${profileManager.getActiveProfileName() ?: "default"} - interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")}}- private fun loadConfigFromIntent(intent: Intent?) {- config = if (intent != null) {- ServiceConfig.fromIntent(intent, dbHelper)- } else {- ServiceConfig.fromDatabase(dbHelper)- }-+ private fun pushConfigToSyncManager() {syncManager.updateConfig(endpoint = config.endpoint,syncIntervalSeconds = config.syncIntervalSeconds,@@ -571,8 +544,18 @@ class LocationForegroundService : Service() {authHeaders = secureStorage.getAuthHeaders(),httpMethod = config.httpMethod)+ }++ private fun loadConfigFromIntent(intent: Intent?) {+ config = if (intent != null) {+ ServiceConfig.fromIntent(intent, dbHelper)+ } else {+ ServiceConfig.fromDatabase(dbHelper)+ }++ pushConfigToSyncManager()- // Store default values so ProfileManager can revert when no profile matches+ // Defaults for ProfileManager to revert to when no profile matchesprofileManager.defaultInterval = config.intervalprofileManager.defaultDistance = config.minUpdateDistanceprofileManager.defaultSyncInterval = config.syncIntervalSecondsdiff --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 0183ad87..02f26eeb 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@@ -83,6 +83,9 @@ class LocationForegroundServiceTest {every { LocationServiceModule.sendTrackingStoppedEvent(any()) } returns trueevery { LocationServiceModule.sendProfileSwitchEvent(any(), any()) } returns true+ mockkStatic(android.os.Looper::class)+ every { android.os.Looper.getMainLooper() } returns mockk(relaxed = true)+service = spyk(LocationForegroundService(), recordPrivateCalls = true)every { service.stopForeground(any<Int>()) } returns Unit@Suppress("DEPRECATION")@@ -96,6 +99,7 @@ class LocationForegroundServiceTest {testScope.cancel()Dispatchers.resetMain()unmockkObject(LocationServiceModule)+ unmockkStatic(android.os.Looper::class)}private fun injectDependencies() {@@ -161,7 +165,7 @@ class LocationForegroundServiceTest {}// =========================================================================- // handleLocationUpdate — full pipeline+ // handleLocationUpdate - full pipeline// =========================================================================@Test@@ -482,6 +486,28 @@ class LocationForegroundServiceTest {verify { payloadBuilder.buildPayload(any(), any(), any(), emptyMap(), any(), any()) }}+ // =========================================================================+ // setupLocationUpdates - error handling+ // =========================================================================++ @Test+ fun `setupLocationUpdates stops service on SecurityException`() {+ every { locationProvider.requestLocationUpdates(any(), any(), any(), any()) } throws SecurityException("no permission")++ invokeSetupLocationUpdates()++ verify { service.stopSelf() }+ }++ @Test+ fun `setupLocationUpdates stops service on generic Exception`() {+ every { locationProvider.requestLocationUpdates(any(), any(), any(), any()) } throws RuntimeException("provider crashed")++ invokeSetupLocationUpdates()++ verify { service.stopSelf() }+ }+// =========================================================================// Lightweight action handlers// =========================================================================@@ -703,7 +729,7 @@ class LocationForegroundServiceTest {}// =========================================================================- // recheckZoneWithLocation — zone recheck state machine+ // recheckZoneWithLocation - zone recheck state machine// =========================================================================@Test@@ -785,7 +811,7 @@ class LocationForegroundServiceTest {}// =========================================================================- // applyProfileConfig — dynamic config switching+ // applyProfileConfig - dynamic config switching// =========================================================================@Test@@ -851,15 +877,10 @@ class LocationForegroundServiceTest {val oldCallback = mockk<LocationUpdateCallback>(relaxed = true)setField("locationUpdateCallback", oldCallback)- mockkStatic(android.os.Looper::class)- every { android.os.Looper.getMainLooper() } returns mockk(relaxed = true)-invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)verify { locationProvider.removeLocationUpdates(oldCallback) }verify { locationProvider.requestLocationUpdates(2000L, 5f, any(), any()) }-- unmockkStatic(android.os.Looper::class)}@Test@@ -869,8 +890,19 @@ class LocationForegroundServiceTest {verify { notificationHelper.update(any(), any(), any(), any(), any(), any(), any(), forceUpdate = true) }}+ @Test+ fun `applyProfileConfig cancels pending locationRestartJob`() {+ val mockJob = mockk<Job>(relaxed = true)+ setField("locationRestartJob", mockJob)++ invokeApplyProfileConfig(interval = 2000L, distance = 5f, syncInterval = 30)++ verify { mockJob.cancel() }+ assertNull(getField<Job?>("locationRestartJob"))+ }+// =========================================================================- // onDestroy — cleanup+ // onDestroy - cleanup// =========================================================================@Test@@ -935,7 +967,7 @@ class LocationForegroundServiceTest {}// =========================================================================- // stopForegroundServiceWithReason — battery critical path+ // stopForegroundServiceWithReason - battery critical path// =========================================================================@Test@@ -981,7 +1013,7 @@ class LocationForegroundServiceTest {}// =========================================================================- // Helpers — invoke private methods via reflection+ // Helpers - invoke private methods via reflection// =========================================================================private fun invokeHandleLocationUpdate(location: Location) {@@ -1034,4 +1066,11 @@ class LocationForegroundServiceTest {method.isAccessible = truemethod.invoke(service)}++ private fun invokeSetupLocationUpdates() {+ val method = LocationForegroundService::class.java+ .getDeclaredMethod("setupLocationUpdates")+ method.isAccessible = true+ method.invoke(service)+ }}diff --git a/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx b/apps/mobile/src/components/ui/FloatingSaveIndicator.tsxindex 1c753099..1f3535a9 100644--- a/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx+++ b/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx@@ -14,14 +14,16 @@ interface Props {success: boolean/** Optional custom message. When provided, controls visibility instead of saving/success. */message?: string | null+ isError?: booleancolors: {info: stringsuccess: string+ error: stringtext: string}}-export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, message, colors }) => {+export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, message, isError, colors }) => {const hasMessage = message != nullconst visible = hasMessage || saving || success@@ -50,8 +52,8 @@ export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, messagstyle={[styles.badge,{- backgroundColor: saving ? colors.info : colors.success,- shadowColor: saving ? colors.info : colors.success+ backgroundColor: saving ? colors.info : isError ? colors.error : colors.success,+ shadowColor: saving ? colors.info : isError ? colors.error : colors.success}]}>diff --git a/apps/mobile/src/screens/DataManagementScreen.tsx b/apps/mobile/src/screens/DataManagementScreen.tsxindex e177372e..51a800a1 100644--- a/apps/mobile/src/screens/DataManagementScreen.tsx+++ b/apps/mobile/src/screens/DataManagementScreen.tsx@@ -94,13 +94,15 @@ export function DataManagementScreen({}: ScreenProps) {setFeedback(`Syncing 0/${total}...`)feedbackTimeout.clear()- // Listen for native progress events during flush+ const receivedProgress = { current: false }+progressListenerRef.current = syncEmitter.addListener("onSyncProgress",(event: { sent: number; failed: number; total: number }) => {+ receivedProgress.current = trueconst processed = event.sent + event.failedif (processed >= event.total) {- // Sync finished — show final result, then clean up+ // Sync finishedconst msg =event.failed > 0? `Synced ${event.sent}/${event.total} (${event.failed} failed)`@@ -116,12 +118,11 @@ export function DataManagementScreen({}: ScreenProps) {})- // manualFlush resolves immediately (fire-and-forget Intent),- // so use a long fallback in case no progress events arrive+ // manualFlush is fire-and-forget; fall back after 30s if no progress events arriveawait NativeLocationService.manualFlush()flushTimeout.set(async () => {await cleanupFlush()- showFeedback("Sync complete")+ showFeedback(receivedProgress.current ? "Sync complete" : "Sync failed! Check connection")}, 30000)} catch (err) {logger.error("[DataManagementScreen] Manual flush error:", err)@@ -346,13 +347,19 @@ export function DataManagementScreen({}: ScreenProps) {</ScrollView>{/* Floating Feedback */}- <FloatingSaveIndicator saving={isProcessing} success={false} message={feedback} colors={colors} />+ <FloatingSaveIndicator+ saving={isProcessing}+ success={false}+ message={feedback}+ isError={feedback?.toLowerCase().includes("failed") ?? false}+ colors={colors}+ /></KeyboardAvoidingView></Container>)}-// --- Reusable ActionRow Component ---+// ActionRow Componentconst ActionRow = ({label,hint,