apps: permission requests happen on tap, with the reason shown
- Commit
2c5812f345e0031338b0fdea2ef6d5464b37dd2a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 11:15 UTC (15 days ago)
- Parents
3199e95
Health auto-launched the Health Connect medical-records request on first entry - a system dialog with no explanation. The auto-launch is deleted; the Medical page now shows a purpose card and only its 'Allow medical records' tap launches the request, falling back to Room on refusal. FindFamily's UWB ranging request likewise fired on screen open; it now waits for the 'Start Find Nearby' tap behind purpose text. Auto's mic card used a raw permission contract that dead-ended on permanent denial; it now uses the shared rememberPermissionRequest, which offers Settings recovery. Verified: compile for health, findfamily and auto; the targeted page/content/consent tests pass.
Diff
auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt b/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.ktindex c57539b979..512710b607 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/MicPermissionCard.kt@@ -2,12 +2,11 @@ package com.vayunmathur.auto.ui import android.Manifest import android.content.pm.PackageManager-import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember@@ -17,6 +16,9 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.auto.R import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card@@ -24,6 +26,7 @@ import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.SettingsSection import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberPermissionRequest /** * Gates voice-reply retention on the microphone permission.@@ -43,9 +46,25 @@ fun MicPermissionCard(modifier: Modifier = Modifier) { PackageManager.PERMISSION_GRANTED, ) }- val requestor = rememberLauncherForActivityResult(- ActivityResultContracts.RequestPermission(),+ // Shared helper: a permanently denied request opens app settings instead of+ // dead-ending (the raw RequestPermission contract returned denied silently).+ val requestMicPermission = rememberPermissionRequest(+ Manifest.permission.RECORD_AUDIO, ) { granted = it }+ // A grant made in Settings produces no result callback, so re-probe on resume.+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) {+ granted = ContextCompat.checkSelfPermission(+ context,+ Manifest.permission.RECORD_AUDIO,+ ) == PackageManager.PERMISSION_GRANTED+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ } Card(modifier.fillMaxWidth()) { Column(Modifier.padding(vertical = 8.dp)) { SettingsSection(title = stringResource(R.string.mic_headline)) {@@ -66,9 +85,7 @@ fun MicPermissionCard(modifier: Modifier = Modifier) { }, trailingContent = { if (!granted) {- Button(onClick = {- requestor.launch(Manifest.permission.RECORD_AUDIO)- }) {+ Button(onClick = requestMicPermission) { Text(stringResource(R.string.mic_allow)) } }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingContent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingContent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingContent.ktindex 6ab130707f..23795cfe03 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingContent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingContent.kt@@ -16,6 +16,7 @@ import com.vayunmathur.findfamily.R import com.vayunmathur.findfamily.platform.RangingSample import com.vayunmathur.findfamily.platform.UwbSessionManager import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.MaterialTheme@@ -32,13 +33,19 @@ import com.vayunmathur.library.ui.IconNavigationArrow /** * The rendered half of [UwbRangingScreen] — no ViewModel, no session lifecycle — so the * store-listing preview can draw it.+ *+ * When [showStart] is true the purpose text and Start button replace the session status:+ * nothing (permission request included) fires until the user taps. Defaults keep the+ * preview/test call sites showing session state directly. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun UwbRangingContent( peerName: String, session: UwbSessionManager.UwbSessionState,- onBack: () -> Unit+ onBack: () -> Unit,+ showStart: Boolean = false,+ onStart: () -> Unit = {}, ) { AppScaffold( title = peerName,@@ -52,6 +59,10 @@ fun UwbRangingContent( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceEvenly ) {+ if (showStart) {+ StartBlock(onStart = onStart)+ return@Column+ } when (val s = session) { UwbSessionManager.UwbSessionState.Idle, UwbSessionManager.UwbSessionState.Starting -> StatusBlock(@@ -86,6 +97,32 @@ fun UwbRangingContent( } } +@Composable+private fun StartBlock(onStart: () -> Unit) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.Center,+ ) {+ Text(+ stringResource(R.string.uwb_permission_title),+ style = MaterialTheme.typography.titleLarge,+ textAlign = TextAlign.Center,+ )+ Spacer(Modifier.height(8.dp))+ Text(+ stringResource(R.string.uwb_permission_body),+ style = MaterialTheme.typography.bodyMedium,+ textAlign = TextAlign.Center,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Spacer(Modifier.height(16.dp))+ Button(onClick = onStart) {+ Text(stringResource(R.string.uwb_start_action))+ }+ }+}+ @Composable private fun StatusBlock(main: String, sub: String? = null, progress: Boolean) { Column(
findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.ktindex bb8508f6eb..47ed7272bc 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/UwbRangingScreen.kt@@ -48,7 +48,9 @@ import com.vayunmathur.library.util.NavBackStack * arrow to the selected peer. * * The screen owns the UWB session lifecycle: it triggers [FindFamilyViewModel.startRanging]- * on first composition and [FindFamilyViewModel.stopRanging] on dispose.+ * only after the user taps Start (which first requests RANGING if needed) and+ * [FindFamilyViewModel.stopRanging] on dispose. Opening the screen never fires the+ * system permission dialog. */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -74,16 +76,27 @@ fun UwbRangingScreen( ) == PackageManager.PERMISSION_GRANTED ) }+ var rangingStarted by remember { mutableStateOf(false) } val requestRangingPermission = rememberPermissionRequest( "android.permission.RANGING"- ) { granted -> hasRangingPermission = granted }+ ) { granted ->+ hasRangingPermission = granted+ if (granted) rangingStarted = true+ } - LaunchedEffect(hasRangingPermission) {- if (!hasRangingPermission) {- requestRangingPermission()- return@LaunchedEffect+ // A session the service already auto-accepted for this peer needs no Start tap —+ // reveal it in place. This never requests permission or starts a session.+ LaunchedEffect(activePeerId, session) {+ if (activePeerId == peerUserId &&+ session !is UwbSessionManager.UwbSessionState.Idle+ ) {+ rangingStarted = true }- // Three cases when the screen opens:+ }++ LaunchedEffect(hasRangingPermission, rangingStarted) {+ if (!rangingStarted || !hasRangingPermission) return@LaunchedEffect+ // Three cases once the user has tapped Start: // (a) session is Idle → user wants to find peer; start as initiator. // (b) session is active for THIS peer → service already auto-accepted; just observe. // (c) session is active for ANOTHER peer → busy; show a Failed state (one session at a time).@@ -112,7 +125,15 @@ fun UwbRangingScreen( UwbRangingContent( peerName = peer?.name ?: stringResource(UiR.string.unknown), session = session,- onBack = { backStack.pop() }+ onBack = { backStack.pop() },+ showStart = !rangingStarted,+ onStart = {+ if (hasRangingPermission) {+ rangingStarted = true+ } else {+ requestRangingPermission()+ }+ }, ) }
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 bbcc44450c..f6e7485d5a 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -278,6 +278,12 @@ <string name="uwb_status_failed">Find Nearby (UWB) failed.</string> <!-- UwbRangingScreen: Status when the other person's phone declined the request because it has no UWB / Find Nearby support. Sentence --> <string name="uwb_status_peer_unsupported">Their phone doesn\'t support Find Nearby.</string>+ <!-- UwbRangingScreen: Title shown before ranging starts, above the permission purpose text. Noun phrase -->+ <string name="uwb_permission_title">Find nearby</string>+ <!-- UwbRangingScreen: Purpose text read before the RANGING permission request. Sentences -->+ <string name="uwb_permission_body">Find Nearby uses ultra-wideband to measure distance and direction to this person. It needs the RANGING permission — tap Start to allow it and begin finding.</string>+ <!-- UwbRangingScreen: Button that requests RANGING (if needed) and starts ranging. Verb phrase -->+ <string name="uwb_start_action">Start Find Nearby</string> <!-- SecurityCodeDialog: Title. Noun phrase --> <string name="security_code">Security code</string>
health/src/main/java/com/vayunmathur/health/MainActivity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/MainActivity.kt b/health/src/main/java/com/vayunmathur/health/MainActivity.ktindex 1a45e1d92a..82bfd769e8 100644--- a/health/src/main/java/com/vayunmathur/health/MainActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/MainActivity.kt@@ -1,6 +1,5 @@ package com.vayunmathur.health -import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect@@ -11,7 +10,6 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.res.stringResource import androidx.health.connect.client.HealthConnectClient-import androidx.health.connect.client.PermissionController import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner@@ -112,11 +110,6 @@ class MainActivity : MaActivity() { return } - val requestMedicalPermissions = rememberLauncherForActivityResult(- contract = PermissionController.createRequestPermissionResultContract(),- onResult = { /* Refusal is fine — the medical screens fall back to local data. */ }- )- AppPermissionsGate( spec = AppPermissionsSpec( title = stringResource(R.string.grant_permissions),@@ -133,19 +126,12 @@ class MainActivity : MaActivity() { LaunchedEffect(Unit) { HealthSyncWorker.enqueue(this@MainActivity) }- // FHIR record access is requested separately and is allowed to fail. It only- // exists on Android 15 with an updated Health Connect module, so folding it- // into PERMISSIONS above would gate the whole app on something most supported- // devices cannot grant; the medical screens work from Room without it.- LaunchedEffect(Unit) {- if (PersonalHealthRecords.isAvailable() &&- ::healthConnectClient.isInitialized &&- !healthConnectClient.permissionController.getGrantedPermissions()- .containsAll(PersonalHealthRecords.PERMISSIONS)- ) {- requestMedicalPermissions.launch(PersonalHealthRecords.PERMISSIONS)- }- }+ // FHIR (PHR) record access is requested separately from the gate above and is+ // allowed to fail: it only exists on Android 15 with an updated Health Connect+ // module, so folding it into PERMISSIONS would gate the whole app on something+ // most supported devices cannot grant. It is requested only from the explicit+ // tap on the Medical tab's permission card (see MedicalPage), never auto-fired+ // here — entering the app must not pop the system dialog with no rationale. Navigation(healthViewModel, medicalViewModel) } }
health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.ktindex 100c94cc02..27b4072e5b 100644--- a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt@@ -101,6 +101,26 @@ object PersonalHealthRecords { } } + /**+ * Whether every [PERMISSIONS] entry is currently granted.+ *+ * Probed by the Medical tab before deciding whether to show its permission card; never+ * launches a request itself. Returns false when the feature or client is unavailable.+ */+ // Broad catch is deliberate: same never-throw contract as [isAvailable] — the client+ // throws undocumented RuntimeExceptions when the module is missing or outdated.+ @Suppress("TooGenericExceptionCaught")+ suspend fun hasAllPermissions(): Boolean {+ val current = client ?: return false+ if (!isAvailable()) return false+ return try {+ current.permissionController.getGrantedPermissions().containsAll(PERMISSIONS)+ } catch (e: Exception) {+ Log.status(TAG, "Could not query granted medical permissions", e)+ false+ }+ }+ // Broad catch is deliberate: this is the availability probe whose contract is to // never throw, and the Health Connect client throws undocumented RuntimeExceptions // (not just declared ones) when the module is missing or outdated.
health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt b/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.ktindex 177ecb65ba..d00a2c0ec9 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt@@ -1,17 +1,26 @@ package com.vayunmathur.health.ui +import androidx.activity.compose.rememberLauncherForActivityResult import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.fillMaxWidth 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.mutableIntStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.unit.dp+import androidx.health.connect.client.PermissionController+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.health.R import com.vayunmathur.health.Route import com.vayunmathur.health.data.AllergyEntry@@ -20,6 +29,7 @@ import com.vayunmathur.health.data.LabResultEntry import com.vayunmathur.health.data.MedicationEntry import com.vayunmathur.health.data.VaccinationEntry import com.vayunmathur.health.platform.MedicalViewModel+import com.vayunmathur.health.platform.PersonalHealthRecords import com.vayunmathur.health.platform.deleteAllergy import com.vayunmathur.health.platform.deleteCondition import com.vayunmathur.health.platform.deleteLabResult@@ -29,6 +39,8 @@ import com.vayunmathur.health.platform.importFromHealthConnect import com.vayunmathur.health.platform.recordDoseTaken import com.vayunmathur.health.ui.components.HealthRow import com.vayunmathur.health.ui.components.MedicalStorageNotice+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.ConfirmDialog import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.ExperimentalMaterial3ExpressiveApi@@ -42,6 +54,7 @@ import com.vayunmathur.library.ui.IconScience import com.vayunmathur.library.ui.IconVaccine import com.vayunmathur.library.ui.IconWarning import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.SwipeActionsBox import com.vayunmathur.library.ui.Text@@ -71,6 +84,31 @@ fun MedicalPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { val labResults by viewModel.labResults.collectAsState() val medications by viewModel.medications.collectAsState() + // PHR (FHIR) access is tap-gated: entering this tab never launches the system+ // dialog. The card below explains the purpose first and only its button fires+ // the request; refusal leaves the Room-backed logs fully usable.+ var phrGranted by remember { mutableStateOf(false) }+ var resumeEpoch by remember { mutableIntStateOf(0) }+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) resumeEpoch+++ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }+ LaunchedEffect(viewModel.healthConnectAvailable, resumeEpoch) {+ if (viewModel.healthConnectAvailable) {+ phrGranted = PersonalHealthRecords.hasAllPermissions()+ }+ }+ val requestPhrPermissions = rememberLauncherForActivityResult(+ contract = PermissionController.createRequestPermissionResultContract(),+ ) { granted ->+ phrGranted = granted.containsAll(PersonalHealthRecords.PERMISSIONS)+ if (phrGranted) viewModel.importFromHealthConnect()+ }+ LaunchedEffect(Unit) { viewModel.importFromHealthConnect() } val expanded = remember { mutableStateListOf<String>() }@@ -211,6 +249,12 @@ fun MedicalPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { ) { if (!viewModel.healthConnectAvailable) { item { MedicalStorageNotice() }+ } else if (!phrGranted) {+ item(key = "medical-phr-permission") {+ MedicalPhrPermissionCard(+ onRequest = { requestPhrPermissions.launch(PersonalHealthRecords.PERMISSIONS) },+ )+ } } item(key = "medical-about-you") {@@ -331,5 +375,25 @@ fun MedicalPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { } } +/**+ * The tap target for PHR access, following the gate-row pattern (Card + ListItem ++ * trailing Grant button) the shared permission gate uses: purpose text is read+ * first, and only the button invokes the Health Connect contract.+ */+@Composable+private fun MedicalPhrPermissionCard(onRequest: () -> Unit) {+ Card(modifier = Modifier.fillMaxWidth()) {+ ListItem(+ headlineContent = { Text(stringResource(R.string.phr_permission_title)) },+ supportingContent = { Text(stringResource(R.string.phr_permission_body)) },+ trailingContent = {+ Button(onClick = onRequest) {+ Text(stringResource(R.string.phr_permission_action))+ }+ },+ )+ }+}+ private const val CATEGORY_VACCINATIONS = "vaccinations" private const val CATEGORY_ALLERGIES = "allergies"
health/src/main/res/values/strings.xml
diff --git a/health/src/main/res/values/strings.xml b/health/src/main/res/values/strings.xmlindex 8c3119fa9c..c329f13df9 100644--- a/health/src/main/res/values/strings.xml+++ b/health/src/main/res/values/strings.xml@@ -292,6 +292,12 @@ <!-- MedicalPage: Banner shown when the device cannot store FHIR records. Sentence --> <string name="phr_unavailable">Health Connect on this device cannot store medical records, so these are kept in the app only.</string>+ <!-- MedicalPage: Title of the card asking for medical-record access. Noun phrase -->+ <string name="phr_permission_title">Medical records in Health Connect</string>+ <!-- MedicalPage: Purpose text shown before the medical-record permission request. Sentences -->+ <string name="phr_permission_body">Allow Health to read and write your medical records — vaccinations, medications, allergies, conditions and lab results — in Health Connect so other health apps can see them. Without this, records stay in this app only.</string>+ <!-- MedicalPage: Button that launches the medical-record permission request. Verb phrase -->+ <string name="phr_permission_action">Allow medical records</string> <!-- MedicalPage: Shown when no records exist in any category. Sentence --> <!-- MedicalPage: FAB entry and add screen title. Verb phrase -->