Modern Apps git

← Modern-Apps.git

findfamily: require fine location, gate service on sharing toggle, fix permission crashes

Commit
2fd83da9f0736919ae884ea4898504774e0a079a
Author
Vayun Mathur <[email protected]>
When
2026-06-23 19:08 UTC (5 months ago)
Parents
368646d

Diff

findfamily/src/main/AndroidManifest.xml
diff --git a/findfamily/src/main/AndroidManifest.xml b/findfamily/src/main/AndroidManifest.xmlindex d1165d2419..e86543b893 100644--- a/findfamily/src/main/AndroidManifest.xml+++ b/findfamily/src/main/AndroidManifest.xml@@ -8,6 +8,7 @@      <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> +    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />     <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.ktindex ccb79ad2db..0b4dfe7496 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/MainActivity.kt@@ -15,16 +15,20 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button+import androidx.compose.material3.AlertDialog import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text+import androidx.compose.material3.TextButton import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource@@ -89,6 +93,7 @@ class MainActivity : ComponentActivity() {         setContent {             DynamicTheme {                 val hasForeground by ffViewModel.hasForeground.collectAsState()+                val hasCoarse by ffViewModel.hasCoarse.collectAsState()                 val hasBackground by ffViewModel.hasBackground.collectAsState()                  // Automatically re-check when returning from System Settings@@ -105,10 +110,10 @@ class MainActivity : ComponentActivity() {                  if (!hasForeground || !hasBackground) {                     NoPermissionsScreen(-                        hasForeground = hasForeground,+                        hasFine = hasForeground,+                        hasCoarse = hasCoarse,                         hasBackground = hasBackground,-                        onForegroundGranted = { ffViewModel.refreshPermissions() },-                        onBackgroundGranted = { ffViewModel.refreshPermissions() }+                        onPermissionsChanged = { ffViewModel.refreshPermissions() }                     )                 } else {                     val deepLinkPeerId = remember {@@ -125,23 +130,41 @@ class MainActivity : ComponentActivity() {  @Composable fun NoPermissionsScreen(-    hasForeground: Boolean,+    hasFine: Boolean,+    hasCoarse: Boolean,     hasBackground: Boolean,-    onForegroundGranted: () -> Unit,-    onBackgroundGranted: () -> Unit+    onPermissionsChanged: () -> Unit ) {-    // Launcher for Fine Location-    val foregroundLauncher = rememberLauncherForActivityResult(-        ActivityResultContracts.RequestPermission()-    ) { isGranted ->-        if (isGranted) onForegroundGranted()+    // The user granted location but only at an approximate (coarse) level.+    // FindFamily requires precise (fine) location.+    val coarseOnly = hasCoarse && !hasFine++    var showUpgradeDialog by remember { mutableStateOf(false) }++    // Request fine AND coarse together. On Android 12+ this is what surfaces the+    // Precise/Approximate choice; requesting fine alone is ignored by the system.+    val locationLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestMultiplePermissions()+    ) { result ->+        onPermissionsChanged()+        val fineGranted = result[Manifest.permission.ACCESS_FINE_LOCATION] == true+        val coarseGranted = result[Manifest.permission.ACCESS_COARSE_LOCATION] == true+        // Approximate-only: prompt the user to upgrade to precise.+        if (!fineGranted && coarseGranted) {+            showUpgradeDialog = true+        }     }      // Launcher for Background Location (Redirects to Settings)     val backgroundLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.RequestPermission()-    ) { isGranted ->-        if (isGranted) onBackgroundGranted()+    ) { onPermissionsChanged() }++    // Auto-surface the upgrade prompt when we first detect approximate-only.+    // It re-fires only when coarseOnly transitions to true, so dismissing it+    // doesn't immediately reopen it โ€” the explicit button below re-opens it.+    LaunchedEffect(coarseOnly) {+        if (coarseOnly) showUpgradeDialog = true     }      Scaffold { padding ->@@ -150,12 +173,33 @@ fun NoPermissionsScreen(             verticalArrangement = Arrangement.Center,             horizontalAlignment = Alignment.CenterHorizontally         ) {-            // STEP 1: Fine Location+            // STEP 1: Precise (Fine) Location             Button(-                onClick = { foregroundLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION) },-                enabled = !hasForeground+                onClick = {+                    locationLauncher.launch(+                        arrayOf(+                            Manifest.permission.ACCESS_FINE_LOCATION,+                            Manifest.permission.ACCESS_COARSE_LOCATION+                        )+                    )+                },+                enabled = !hasFine             ) {-                Text(if (hasForeground) stringResource(R.string.permission_fine_location_granted) else stringResource(R.string.permission_grant_fine_location))+                Text(if (hasFine) stringResource(R.string.permission_fine_location_granted) else stringResource(R.string.permission_grant_fine_location))+            }++            // Approximate-only: explain and offer a reliable way to re-open the+            // upgrade prompt after it has been dismissed.+            if (coarseOnly) {+                Text(+                    text = stringResource(R.string.permission_approximate_only_explanation),+                    textAlign = TextAlign.Center,+                    style = MaterialTheme.typography.bodySmall,+                    modifier = Modifier.padding(horizontal = 32.dp, vertical = 8.dp)+                )+                Button(onClick = { showUpgradeDialog = true }) {+                    Text(stringResource(R.string.permission_reopen_upgrade_prompt))+                }             }              Spacer(Modifier.height(16.dp))@@ -163,13 +207,13 @@ fun NoPermissionsScreen(             // STEP 2: Background Location             Button(                 onClick = { backgroundLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) },-                enabled = hasForeground && !hasBackground+                enabled = hasFine && !hasBackground             ) {                 val label = if (hasBackground) stringResource(R.string.permission_background_granted) else stringResource(R.string.permission_enable_all_the_time)                 Text(label)             } -            if (hasForeground && !hasBackground) {+            if (hasFine && !hasBackground) {                 Text(                     text = stringResource(R.string.permission_background_explanation),                     textAlign = TextAlign.Center,@@ -179,6 +223,32 @@ fun NoPermissionsScreen(             }         }     }++    if (showUpgradeDialog) {+        AlertDialog(+            onDismissRequest = { showUpgradeDialog = false },+            title = { Text(stringResource(R.string.permission_upgrade_dialog_title)) },+            text = { Text(stringResource(R.string.permission_upgrade_dialog_message)) },+            confirmButton = {+                TextButton(onClick = {+                    showUpgradeDialog = false+                    locationLauncher.launch(+                        arrayOf(+                            Manifest.permission.ACCESS_FINE_LOCATION,+                            Manifest.permission.ACCESS_COARSE_LOCATION+                        )+                    )+                }) {+                    Text(stringResource(R.string.permission_upgrade_dialog_confirm))+                }+            },+            dismissButton = {+                TextButton(onClick = { showUpgradeDialog = false }) {+                    Text(stringResource(R.string.permission_upgrade_dialog_dismiss))+                }+            }+        )+    } }  @Composable
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex abff161a49..b3a95e9c1b 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -320,7 +320,7 @@ fun MainPage(                                         Checkbox(                                             user.sendingEnabled,                                             { send ->-                                                ffViewModel.upsertUser(user.copy(sendingEnabled = send))+                                                ffViewModel.setUserSharing(user, send)                                             })                                     }                                 }
findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.ktindex 4d486723a9..a31cd9d171 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/BootReceiver.kt@@ -1,16 +1,26 @@ package com.vayunmathur.findfamily.util-import android.Manifest import android.content.BroadcastReceiver import android.content.Context import android.content.Intent-import android.content.pm.PackageManager-import androidx.core.content.ContextCompat+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch  class BootReceiver : BroadcastReceiver() {     override fun onReceive(context: Context, intent: Intent) {         if (intent.action == Intent.ACTION_BOOT_COMPLETED || intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) {-            if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED)-                context.startForegroundService(Intent(context, LocationTrackingService::class.java))+            // Only start when fine location is granted; the sharing-enabled check+            // (and the actual start/stop) is handled by syncServiceState.+            if (!LocationServiceController.hasFineLocationPermission(context)) return+            val pending = goAsync()+            val appContext = context.applicationContext+            CoroutineScope(Dispatchers.IO).launch {+                try {+                    LocationServiceController.syncServiceState(appContext)+                } finally {+                    pending.finish()+                }+            }         }     }-}\ No newline at end of file+}
findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.ktindex 282dd7874f..10b465e82e 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/FindFamilyViewModel.kt@@ -110,12 +110,19 @@ class FindFamilyViewModel(     // ------------------------------------------------------------------      fun deleteUser(user: User) {-        viewModelScope.launch(Dispatchers.IO) { userDao.delete(user) }+        viewModelScope.launch(Dispatchers.IO) {+            userDao.delete(user)+            LocationServiceController.syncServiceState(ctx)+        }     }      fun upsertUser(user: User, onDone: () -> Unit = {}) {         viewModelScope.launch(Dispatchers.IO) {             userDao.upsert(user)+            // A new/updated connection can change whether sharing is enabled, so+            // reconcile the tracking service (e.g. start it after the first+            // person is added).+            LocationServiceController.syncServiceState(ctx)             withContext(Dispatchers.Main) { onDone() }         }     }@@ -246,6 +253,16 @@ class FindFamilyViewModel(     )     val hasForeground: StateFlow<Boolean> = _hasForeground.asStateFlow() +    private val _hasCoarse = MutableStateFlow(+        ContextCompat.checkSelfPermission(+            ctx,+            Manifest.permission.ACCESS_COARSE_LOCATION+        ) == PackageManager.PERMISSION_GRANTED+    )+    /** Approximate (coarse) location permission. The app requires fine; this is+     * only used to detect the "approximate only" case and prompt for an upgrade. */+    val hasCoarse: StateFlow<Boolean> = _hasCoarse.asStateFlow()+     private val _hasBackground = MutableStateFlow(         ContextCompat.checkSelfPermission(             ctx,@@ -254,16 +271,40 @@ class FindFamilyViewModel(     )     val hasBackground: StateFlow<Boolean> = _hasBackground.asStateFlow() -    /** Re-read both permission flags from the OS. Call on resume. */+    /** Re-read all permission flags from the OS and reconcile the tracking+     * service. Call on resume so returning from Settings (grant, revoke,+     * downgrade to approximate, "Only this time" expiry) takes effect. */     fun refreshPermissions() {         _hasForeground.value = ContextCompat.checkSelfPermission(             ctx,             Manifest.permission.ACCESS_FINE_LOCATION         ) == PackageManager.PERMISSION_GRANTED+        _hasCoarse.value = ContextCompat.checkSelfPermission(+            ctx,+            Manifest.permission.ACCESS_COARSE_LOCATION+        ) == PackageManager.PERMISSION_GRANTED         _hasBackground.value = ContextCompat.checkSelfPermission(             ctx,             Manifest.permission.ACCESS_BACKGROUND_LOCATION         ) == PackageManager.PERMISSION_GRANTED+        syncLocationService()+    }++    /** Reconcile the background service with the current permission + sharing+     * state (start if eligible, stop otherwise). */+    fun syncLocationService() {+        viewModelScope.launch(Dispatchers.IO) {+            LocationServiceController.syncServiceState(ctx)+        }+    }++    /** Toggle per-person location sharing and reconcile the service so it stops+     * when nobody is being shared with and starts when sharing is (re)enabled. */+    fun setUserSharing(user: User, enabled: Boolean) {+        viewModelScope.launch(Dispatchers.IO) {+            userDao.upsert(user.copy(sendingEnabled = enabled))+            LocationServiceController.syncServiceState(ctx)+        }     }      // ------------------------------------------------------------------
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 2ade33e22d..73da816114 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/LocationTrackingService.kt@@ -1,4 +1,5 @@ package com.vayunmathur.findfamily.util+import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager@@ -6,6 +7,7 @@ import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent+import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.location.Address import android.location.Geocoder@@ -23,6 +25,7 @@ import android.os.Build import android.os.IBinder import android.os.PowerManager import androidx.core.app.NotificationCompat+import androidx.core.content.ContextCompat import kotlinx.coroutines.* import kotlin.math.sqrt import androidx.work.CoroutineWorker@@ -270,13 +273,35 @@ class LocationTrackingService : Service(), SensorEventListener {     }      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        // Defensive: never run location tracking without fine-location permission.+        // The service can be (re)started by the OS, WorkManager, or BootReceiver,+        // and the permission may have been revoked since it was scheduled+        // (e.g. "Only this time" grant expiring, or the user switching to+        // approximate-only / "Ask every time" / "Don't allow").+        if (!LocationServiceController.hasFineLocationPermission(this)) {+            // We were started via startForegroundService and must satisfy the+            // foreground-start contract. Use the type-less startForeground so it+            // doesn't throw without the location permission, then stop.+            try {+                startForeground(NOTIFICATION_ID, createNotification())+            } catch (_: Exception) {+            }+            stopSelf()+            return START_NOT_STICKY+        }+         val notification = createNotification() -        startForeground(-            NOTIFICATION_ID,-            notification,-            ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION-        )+        try {+            startForeground(+                NOTIFICATION_ID,+                notification,+                ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION+            )+        } catch (_: Exception) {+            stopSelf()+            return START_NOT_STICKY+        }          startTracking()         return START_STICKY@@ -318,6 +343,13 @@ class LocationTrackingService : Service(), SensorEventListener {             heartbeatJob?.cancel()             heartbeatJob = launch {                 while (isActive) {+                    // "Only this time" grants are revoked once the app leaves the+                    // foreground; detect that here and shut down gracefully rather+                    // than spinning (or crashing) on location access we can't make.+                    if (!LocationServiceController.hasFineLocationPermission(this@LocationTrackingService)) {+                        withContext(Dispatchers.Main) { stopSelf() }+                        break+                    }                     syncHeartbeat()                     delay(30.seconds)                 }@@ -524,11 +556,18 @@ class LocationTrackingService : Service(), SensorEventListener {     override fun onDestroy() {         super.onDestroy()         serviceScope.cancel()-        sensorManager.unregisterListener(this)-        significantMotionSensor?.let {-            sensorManager.cancelTriggerSensor(triggerEventListener, it)+        // These are only initialized once startTracking()/registerSensors() runs.+        // The service can be destroyed before that (e.g. stopped immediately in+        // onStartCommand when permission is missing), so guard every access.+        if (::sensorManager.isInitialized) {+            sensorManager.unregisterListener(this)+            significantMotionSensor?.let {+                sensorManager.cancelTriggerSensor(triggerEventListener, it)+            }+        }+        if (::locationManager.isInitialized) {+            stopTrackingUpdates()         }-        stopTrackingUpdates()         stopForeground(STOP_FOREGROUND_REMOVE)     } }@@ -571,13 +610,72 @@ class ServiceRestartWorker( ) : CoroutineWorker(appContext, workerParams) {      override suspend fun doWork(): Result = try {-        applicationContext.startForegroundService(Intent(applicationContext, LocationTrackingService::class.java))+        // Reconcile the service with the current state: only run when fine+        // location is granted AND the user is sharing with at least one person.+        LocationServiceController.syncServiceState(applicationContext)         Result.success()     } catch (_: Exception) {         Result.retry()     } } +/**+ * Single source of truth for whether the [LocationTrackingService] should be+ * running and for (re)starting / stopping it accordingly.+ *+ * The service must only run when BOTH conditions hold:+ *  - fine (precise) location permission is granted (the app does not work with+ *    approximate-only location), and+ *  - location sharing is enabled for at least one connected person (the+ *    per-person "share your location with this person" toggle).+ */+object LocationServiceController {++    fun hasFineLocationPermission(context: Context): Boolean =+        ContextCompat.checkSelfPermission(+            context,+            Manifest.permission.ACCESS_FINE_LOCATION+        ) == PackageManager.PERMISSION_GRANTED++    /**+     * True iff the user is sharing their location with at least one *other*+     * person (the self user is excluded). Reads directly from the DB so the+     * answer is correct regardless of whether the UI/ViewModel is alive.+     */+    suspend fun isSharingEnabled(context: Context): Boolean {+        val selfId = DataStoreUtils.getInstance(context).getLong("userid")+        val db = context.buildDatabase<FFDatabase>()+        return db.userDao().getAll().any { it.sendingEnabled && it.id != selfId }+    }++    /**+     * Start the service if eligible, otherwise make sure it is stopped. Safe to+     * call from any context (worker, boot, ViewModel, permission refresh).+     */+    suspend fun syncServiceState(context: Context) {+        val appContext = context.applicationContext+        val eligible = hasFineLocationPermission(appContext) && isSharingEnabled(appContext)+        val intent = Intent(appContext, LocationTrackingService::class.java)+        withContext(Dispatchers.Main) {+            if (eligible) {+                try {+                    appContext.startForegroundService(intent)+                } catch (_: Exception) {+                }+            } else {+                appContext.stopService(intent)+            }+        }+    }++    /** Unconditionally stop the service. */+    fun stop(context: Context) {+        context.applicationContext.stopService(+            Intent(context.applicationContext, LocationTrackingService::class.java)+        )+    }+}+ fun ensureSync(context: Context) {     startRepeatedTask<ServiceRestartWorker>(         context, "Location Sync", 15.minutes,
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex 10f5af593a..0968211ea9 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -24,6 +24,12 @@     <string name="permission_background_granted">โœ… Background Granted</string>     <string name="permission_enable_all_the_time">2. Enable \'Allow all the time\'</string>     <string name="permission_background_explanation">To enable background tracking, please select \'Allow all the time\' in the next screen.</string>+    <string name="permission_approximate_only_explanation">FindFamily only works with precise (fine) location. You granted approximate location only โ€” please upgrade to precise location to continue.</string>+    <string name="permission_reopen_upgrade_prompt">Upgrade to precise location</string>+    <string name="permission_upgrade_dialog_title">Precise location required</string>+    <string name="permission_upgrade_dialog_message">FindFamily needs precise (fine) location to share your exact position. Please allow precise location.</string>+    <string name="permission_upgrade_dialog_confirm">Allow precise location</string>+    <string name="permission_upgrade_dialog_dismiss">Not now</string>      <!-- MainPage FAB menu -->     <string name="fab_person">Person</string>