things: add first-run permission gate for bluetooth and health connect
- Commit
2f19106fa05520505b928d13e877dcac4ab570a9- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-06 22:59 UTC (3 months ago)
- Parents
a2605fa
Diff
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex 7c10fbcccd..571f98c41a 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -6,6 +6,7 @@ import androidx.compose.material.icons.filled.CallEnd import androidx.compose.material.icons.filled.Dialpad import androidx.compose.material.icons.filled.Poll import androidx.compose.material.icons.filled.PersonAdd+import androidx.compose.material.icons.filled.Bluetooth import androidx.compose.material.icons.filled.HealthAndSafety import androidx.compose.material.icons.filled.Medication import androidx.compose.material.icons.filled.MonitorHeart@@ -1166,6 +1167,10 @@ fun IconApps(modifier: Modifier = Modifier, tint: Color = LocalContentColor.curr fun IconWidgets(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.Widgets, "Widgets", modifier, tint) +@Composable+fun IconBluetooth(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Bluetooth, "Bluetooth", modifier, tint)+ /** Removing the app itself, as opposed to [IconDelete], which only takes it off a screen. */ @Composable fun IconUninstall(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =
things/src/main/java/com/vayunmathur/things/MainActivity.kt
diff --git a/things/src/main/java/com/vayunmathur/things/MainActivity.kt b/things/src/main/java/com/vayunmathur/things/MainActivity.ktindex 8c79c512a6..2311963457 100644--- a/things/src/main/java/com/vayunmathur/things/MainActivity.kt+++ b/things/src/main/java/com/vayunmathur/things/MainActivity.kt@@ -1,27 +1,56 @@ package com.vayunmathur.things import android.Manifest+import android.content.Intent+import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.core.content.ContextCompat+import androidx.core.net.toUri+import androidx.health.connect.client.HealthConnectClient+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.openAppSettings import com.vayunmathur.things.platform.DeviceController import com.vayunmathur.things.platform.DeviceService import com.vayunmathur.things.platform.HealthConnectHelper+import com.vayunmathur.things.ui.PermissionState+import com.vayunmathur.things.ui.PermissionsPage class MainActivity : ComponentActivity() { // Which scan to run once BLE permissions are granted (the launcher can't tell otherwise). private var pendingScan: (() -> Unit)? = null + // Bumped by every permission result so the gate below re-checks. A plain counter rather than+ // caching the answers, because the system is the source of truth and it can change while we+ // are backgrounded.+ private val permissionEpoch = mutableIntStateOf(0)++ // A denied runtime permission that no longer offers a rationale has been permanently denied —+ // but that is also true before the very first ask, so it only tells us anything afterwards.+ private var hasAskedBluetooth = false+ private val permissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { grants -> val action = pendingScan pendingScan = null+ hasAskedBluetooth = true // Only the BLE perms gate scanning; POST_NOTIFICATIONS only affects notification visibility. val bleGranted = grants[Manifest.permission.BLUETOOTH_SCAN] == true && grants[Manifest.permission.BLUETOOTH_CONNECT] == true@@ -29,15 +58,14 @@ class MainActivity : ComponentActivity() { DeviceService.start(this) action() }+ permissionEpoch.intValue++ } // Health Connect permission contract (mirrors health app). No-op if HC not available. private val healthPermissionLauncher = registerForActivityResult( HealthConnectHelper.permissionsContract()- ) { granted ->- if (granted.containsAll(HealthConnectHelper.requiredPermissions)) {- // Permissions granted — next writes will succeed.- }+ ) {+ permissionEpoch.intValue++ } private fun requestScan(scan: () -> Unit) {@@ -61,6 +89,40 @@ class MainActivity : ComponentActivity() { healthPermissionLauncher.launch(HealthConnectHelper.requiredPermissions) } + private fun bluetoothPermissionState(): PermissionState {+ val granted = BLE_REQUIRED.all {+ ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED+ }+ if (granted) return PermissionState.Granted+ val canAsk = BLE_REQUIRED.any { shouldShowRequestPermissionRationale(it) }+ return if (canAsk || !hasAskedBluetooth) PermissionState.Needed else PermissionState.Blocked+ }++ private suspend fun healthConnectPermissionState(): PermissionState {+ if (HealthConnectHelper.availabilityStatus(this) != HealthConnectClient.SDK_AVAILABLE) {+ return PermissionState.Blocked+ }+ return try {+ val client = HealthConnectClient.getOrCreate(this)+ if (HealthConnectHelper.hasAllPermissions(client)) {+ PermissionState.Granted+ } else {+ PermissionState.Needed+ }+ } catch (_: Exception) {+ PermissionState.Blocked+ }+ }++ /**+ * Health Connect is part of the platform from Android 14, but below that it is an installable+ * app — so "unavailable" is usually fixable and must not dead-end the gate.+ */+ private fun resolveHealthConnect() {+ val intent = Intent(Intent.ACTION_VIEW, "market://details?id=$HEALTH_CONNECT_PACKAGE".toUri())+ if (intent.resolveActivity(packageManager) != null) startActivity(intent) else openAppSettings(this)+ }+ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()@@ -70,28 +132,75 @@ class MainActivity : ComponentActivity() { if (DeviceController.hasRememberedDevice()) DeviceService.start(this) setContent { DynamicTheme {- Navigation(- onScanClick = { requestScan { DeviceController.startBottleScan() } },- onDeviceClick = {- DeviceService.start(this)- DeviceController.connectBottle(it.address)- },- onForgetBottle = {- DeviceController.disconnectBottle()- if (!DeviceController.hasRememberedDevice()) DeviceService.stop(this)- },- onScaleScanClick = { requestScan { DeviceController.startScaleScan() } },- onScaleDeviceClick = {- DeviceService.start(this)- DeviceController.connectScale(it.address)- },- onForgetScale = {- DeviceController.disconnectScale()- if (!DeviceController.hasRememberedDevice()) DeviceService.stop(this)- },- onHealthConnectClick = { requestHealthConnectPermissions() },- )+ PermissionGate {+ Navigation(+ onScanClick = { requestScan { DeviceController.startBottleScan() } },+ onDeviceClick = {+ DeviceService.start(this)+ DeviceController.connectBottle(it.address)+ },+ onForgetBottle = {+ DeviceController.disconnectBottle()+ if (!DeviceController.hasRememberedDevice()) DeviceService.stop(this)+ },+ onScaleScanClick = { requestScan { DeviceController.startScaleScan() } },+ onScaleDeviceClick = {+ DeviceService.start(this)+ DeviceController.connectScale(it.address)+ },+ onForgetScale = {+ DeviceController.disconnectScale()+ if (!DeviceController.hasRememberedDevice()) DeviceService.stop(this)+ },+ onHealthConnectClick = { requestHealthConnectPermissions() },+ )+ } } } }++ /** Shows [content] only once both permissions are in place; otherwise the first-run screen. */+ @Composable+ private fun PermissionGate(content: @Composable () -> Unit) {+ val epoch = permissionEpoch.intValue+ // Permissions can also be changed from system settings while we are backgrounded, which+ // produces no result callback — so re-check whenever we come back to the foreground.+ var resumes by remember { mutableIntStateOf(0) }+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) resumes+++ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }++ val bluetooth = remember(epoch, resumes) { bluetoothPermissionState() }+ var healthConnect by remember { mutableStateOf<PermissionState?>(null) }+ LaunchedEffect(epoch, resumes) { healthConnect = healthConnectPermissionState() }++ // Null until the first async Health Connect check finishes; showing the gate in the+ // meantime would flash it in front of users who granted everything long ago.+ val health = healthConnect ?: return+ if (bluetooth == PermissionState.Granted && health == PermissionState.Granted) {+ content()+ } else {+ PermissionsPage(+ bluetooth = bluetooth,+ healthConnect = health,+ onRequestBluetooth = { permissionLauncher.launch(blePermissions()) },+ onRequestHealthConnect = { requestHealthConnectPermissions() },+ onResolveBluetooth = { openAppSettings(this) },+ onResolveHealthConnect = { resolveHealthConnect() },+ )+ }+ }++ private companion object {+ val BLE_REQUIRED = arrayOf(+ Manifest.permission.BLUETOOTH_SCAN,+ Manifest.permission.BLUETOOTH_CONNECT,+ )+ const val HEALTH_CONNECT_PACKAGE = "com.google.android.apps.healthdata"+ } }
things/src/main/java/com/vayunmathur/things/ui/PermissionsPage.kt
diff --git a/things/src/main/java/com/vayunmathur/things/ui/PermissionsPage.kt b/things/src/main/java/com/vayunmathur/things/ui/PermissionsPage.ktnew file mode 100644index 0000000000..ad9e1eb019--- /dev/null+++ b/things/src/main/java/com/vayunmathur/things/ui/PermissionsPage.kt@@ -0,0 +1,149 @@+package com.vayunmathur.things.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconBluetooth+import com.vayunmathur.library.ui.IconHealth+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.things.R++/** Whether a permission the app needs has been granted, and if not, what can be done about it. */+enum class PermissionState {+ Granted,++ /** Not granted yet; asking in-app will show the system prompt. */+ Needed,++ /**+ * Asking again does nothing — either the user permanently denied it, or Health Connect is+ * missing from the device. Only system settings can resolve it.+ */+ Blocked,+}++/**+ * First-run gate. The app is a bridge between two BLE devices and Health Connect, so without+ * Bluetooth it cannot read anything and without Health Connect it has nowhere to put what it+ * reads — neither permission is optional, and there is no useful UI to show until both are in+ * place.+ *+ * Each permission is requested separately because they use different contracts: Bluetooth is an+ * ordinary runtime permission, Health Connect has its own.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PermissionsPage(+ bluetooth: PermissionState,+ healthConnect: PermissionState,+ onRequestBluetooth: () -> Unit,+ onRequestHealthConnect: () -> Unit,+ onResolveBluetooth: () -> Unit,+ onResolveHealthConnect: () -> Unit,+) {+ AppScaffold(+ title = stringResource(R.string.app_name),+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 16.dp, vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Text(+ stringResource(R.string.permissions_title),+ style = MaterialTheme.typography.headlineSmall,+ )+ Text(+ stringResource(R.string.permissions_rationale),+ style = MaterialTheme.typography.bodyMedium,+ )++ PermissionCard(+ state = bluetooth,+ name = stringResource(R.string.permission_bluetooth),+ reason = stringResource(R.string.permission_bluetooth_reason),+ onRequest = onRequestBluetooth,+ onResolve = onResolveBluetooth,+ icon = { IconBluetooth() },+ )+ PermissionCard(+ state = healthConnect,+ name = stringResource(R.string.permission_health_connect),+ reason = stringResource(R.string.permission_health_connect_reason),+ onRequest = onRequestHealthConnect,+ onResolve = onResolveHealthConnect,+ icon = { IconHealth() },+ )+ }+ }+}++@Composable+private fun PermissionCard(+ state: PermissionState,+ name: String,+ reason: String,+ onRequest: () -> Unit,+ onResolve: () -> Unit,+ icon: @Composable () -> Unit,+) {+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ icon()+ Text(name, style = MaterialTheme.typography.titleMedium)+ }+ Text(reason, style = MaterialTheme.typography.bodyMedium)+ when (state) {+ PermissionState.Granted -> Text(+ stringResource(R.string.permission_granted),+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.primary,+ )+ PermissionState.Needed -> Button(onClick = onRequest) {+ Text(stringResource(R.string.permission_grant))+ }+ // An in-app request is a no-op once permanently denied, so send them somewhere+ // that can actually change the answer.+ PermissionState.Blocked -> {+ Text(+ stringResource(R.string.permission_blocked),+ style = MaterialTheme.typography.bodySmall,+ )+ TextButton(onClick = onResolve) {+ Text(stringResource(R.string.permission_open_settings))+ }+ }+ }+ }+ }+}
things/src/main/res/values/strings.xml
diff --git a/things/src/main/res/values/strings.xml b/things/src/main/res/values/strings.xmlindex 15a7142d2b..a307feffcd 100644--- a/things/src/main/res/values/strings.xml+++ b/things/src/main/res/values/strings.xml@@ -75,6 +75,28 @@ <!-- Button to grant Health Connect permissions. Verb phrase --> <string name="health_connect">Health Connect</string> + <!-- First-run permission screen -->+ <!-- Headline on the first-run permission screen. Sentence -->+ <string name="permissions_title">Permissions needed</string>+ <!-- Explains why the app cannot start without both permissions. Sentence -->+ <string name="permissions_rationale">Things reads your bottle and scale over Bluetooth and saves the readings to Health Connect. It needs both to work.</string>+ <!-- Name of the Bluetooth permission on the first-run screen. Noun -->+ <string name="permission_bluetooth">Bluetooth</string>+ <!-- Why the app needs Bluetooth. Sentence -->+ <string name="permission_bluetooth_reason">To find and stay connected to your water bottle and body scale.</string>+ <!-- Name of the Health Connect permission on the first-run screen. Noun -->+ <string name="permission_health_connect">Health Connect</string>+ <!-- Why the app needs Health Connect. Sentence -->+ <string name="permission_health_connect_reason">To save your hydration and body measurements. This app stores nothing itself.</string>+ <!-- Shown on a permission card once the permission has been granted. Adjective -->+ <string name="permission_granted">Granted</string>+ <!-- Button that asks the system for a permission. Verb -->+ <string name="permission_grant">Grant</string>+ <!-- Shown when a permission was permanently denied and can only be changed in settings -->+ <string name="permission_blocked">This has to be turned on in system settings.</string>+ <!-- Button that opens this app's page in system settings. Verb phrase -->+ <string name="permission_open_settings">Open settings</string>+ <!-- Foreground service --> <!-- Notification channel name for the ongoing "keeping devices connected" notification --> <string name="device_channel_name">Device connection</string>