Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

refactor: replace direct Health Connect permission contract with a robust, fallback-supporting intent resolution helper

Rishabh Bajpai26cdbd909a39
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 5b67359..c641401 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -172,19 +172,27 @@ class MainActivity : ComponentActivity() {
}
/**
- * Health Connect uses its own permission contract rather than the standard
- * runtime dialog, so it needs a launcher of its own.
+ * Health Connect uses its own permission screen rather than the standard
+ * runtime dialog. The intent is built by [requestHealthConnect], which picks
+ * the SDK's permission screen or a fallback that can actually be resolved
+ * on the device; the grant state is re-read from the provider when the user
+ * returns, because the fallback screens carry no useful result of their own.
*/
private val healthConnectLauncher = registerForActivityResult(
- androidx.health.connect.client.PermissionController.createRequestPermissionResultContract()
- ) { granted ->
- com.gotcha.tools.HealthPermissionState.set(granted.isNotEmpty())
- val message = if (granted.isEmpty()) {
- "No health permissions granted."
- } else {
- "Health Connect: ${granted.size} permission(s) granted."
+ ActivityResultContracts.StartActivityForResult()
+ ) {
+ lifecycleScope.launch {
+ val granted = com.gotcha.tools.HealthPermissionState.refresh(this@MainActivity)
+ Toast.makeText(
+ this@MainActivity,
+ if (granted) {
+ "Health Connect: permissions granted."
+ } else {
+ "No health permissions granted."
+ },
+ Toast.LENGTH_SHORT
+ ).show()
}
- Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
/**
@@ -391,30 +399,23 @@ class MainActivity : ComponentActivity() {
}
/**
- * Opens Health Connect's permission screen, or steers to the Play listing when
- * no provider is installed (Android 13 and below ship it as a separate app).
+ * Opens Health Connect's permission screen, or the nearest thing that can
+ * actually be resolved on this device. Never crashes: the intent is chosen
+ * by [com.gotcha.tools.healthConnectPermissionIntent], which only returns
+ * something with a resolver, and the launch itself goes through the
+ * activity-result launcher.
*/
private fun requestHealthConnect() {
- val status = androidx.health.connect.client.HealthConnectClient.getSdkStatus(this)
- if (status == androidx.health.connect.client.HealthConnectClient.SDK_AVAILABLE) {
- healthConnectLauncher.launch(com.gotcha.tools.HealthTool.PERMISSIONS)
- return
- }
- Toast.makeText(
- this,
- "Health Connect is not available — install or update it from the Play Store.",
- Toast.LENGTH_LONG
- ).show()
- runCatching {
- startActivity(
- Intent(
- Intent.ACTION_VIEW,
- android.net.Uri.parse(
- "market://details?id=com.google.android.apps.healthdata"
- )
- )
- )
+ if (androidx.health.connect.client.HealthConnectClient.getSdkStatus(this) !=
+ androidx.health.connect.client.HealthConnectClient.SDK_AVAILABLE
+ ) {
+ Toast.makeText(
+ this,
+ "Health Connect is not available — install or update it from the Play Store.",
+ Toast.LENGTH_LONG
+ ).show()
}
+ com.gotcha.tools.healthConnectPermissionIntent(this)?.let { healthConnectLauncher.launch(it) }
}
override fun onNewIntent(intent: Intent) {
diff --git a/app/src/main/java/com/gotcha/tools/HealthTool.kt b/app/src/main/java/com/gotcha/tools/HealthTool.kt
index 5effaf5..2f5cc0e 100644
--- a/app/src/main/java/com/gotcha/tools/HealthTool.kt
+++ b/app/src/main/java/com/gotcha/tools/HealthTool.kt
@@ -1,7 +1,10 @@
package com.gotcha.tools
import android.content.Context
+import android.content.Intent
+import android.net.Uri
import androidx.health.connect.client.HealthConnectClient
+import androidx.health.connect.client.PermissionController
import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.aggregate.AggregationResult
import androidx.health.connect.client.permission.HealthPermission
@@ -90,6 +93,14 @@ class HealthTool(private val context: Context) {
)
val RECORD_TYPE_NAMES: List<String> = RECORD_TYPES.keys.toList()
+
+ /** Android 14+ platform action for Health Connect's per-app permission manager. */
+ const val ACTION_MANAGE_HEALTH_PERMISSIONS =
+ "android.health.connect.action.MANAGE_HEALTH_PERMISSIONS"
+
+ internal const val PLAY_LISTING_URI = "market://details?id=com.google.android.apps.healthdata"
+ internal const val CONTROLLER_PACKAGE = "com.google.android.healthconnect.controller"
+ internal const val LEGACY_PROVIDER_PACKAGE = "com.google.android.apps.healthdata"
}
private fun clientOrNull(): HealthConnectClient? =
@@ -242,3 +253,54 @@ class HealthTool(private val context: Context) {
else -> record.javaClass.simpleName
}
}
+
+/**
+ * The Health Connect permission intent to fire, or the best fallback that can
+ * actually be resolved on this device. Never null when the Play Store is
+ * reachable and never throws.
+ *
+ * On API 34+ the SDK's `PermissionController` contract builds its intent from
+ * `ActivityResultContracts.RequestMultiplePermissions`, which stock Android
+ * routes to the Health Connect screen but some OEM builds do not resolve at
+ * all — firing it blind throws `ActivityNotFoundException` (the crash this
+ * guards against). Each candidate is therefore only used when it has a
+ * resolver, and the chain degrades to the Health Connect app itself rather
+ * than a crash. Shared by the Settings permission row and the agent path.
+ */
+fun healthConnectPermissionIntent(context: Context): Intent? {
+ if (HealthConnectClient.getSdkStatus(context) != HealthConnectClient.SDK_AVAILABLE) {
+ // No provider (or one that is out of date): steer to the Play listing
+ // instead of crash-launching a screen nothing can handle.
+ return Intent(Intent.ACTION_VIEW, Uri.parse(HealthTool.PLAY_LISTING_URI))
+ }
+ val pm = context.packageManager
+ // Preferred: the SDK's permission-request screen (parses the granted set on
+ // the way back). Only used when something actually resolves it.
+ runCatching {
+ PermissionController.createRequestPermissionResultContract()
+ .createIntent(context, HealthTool.PERMISSIONS)
+ }.getOrNull()?.let { intent ->
+ if (intent.resolveActivity(pm) != null) return intent
+ }
+ // Fallback: the Health Connect home screen. This is the reliable opener on
+ // OEM builds whose per-app permission page refuses to show (launches and
+ // immediately finishes) for an app with no grants yet — the home always
+ // opens, and the user reaches App permissions from there.
+ Intent(HealthConnectClient.ACTION_HEALTH_CONNECT_SETTINGS)
+ .takeIf { it.resolveActivity(pm) != null }
+ ?.let { return it }
+ // Fallback: Health Connect's per-app permission manager (Android 14+), for
+ // devices where it does show the target app directly.
+ healthConnectManagePermissionsIntent(context)
+ .takeIf { it.resolveActivity(pm) != null }
+ ?.let { return it }
+ // Last resort: open the Health Connect app so the user can grant from there.
+ pm.getLaunchIntentForPackage(HealthTool.CONTROLLER_PACKAGE)?.let { return it }
+ pm.getLaunchIntentForPackage(HealthTool.LEGACY_PROVIDER_PACKAGE)?.let { return it }
+ return null
+}
+
+/** The per-app Health Connect permission manager intent (Android 14+ platform action). */
+internal fun healthConnectManagePermissionsIntent(context: Context): Intent =
+ Intent(HealthTool.ACTION_MANAGE_HEALTH_PERMISSIONS)
+ .putExtra(Intent.EXTRA_PACKAGE_NAME, context.packageName)
diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
index 633af08..29e9892 100644
--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
@@ -33,15 +33,14 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
-import androidx.health.connect.client.HealthConnectClient
-import androidx.health.connect.client.PermissionController
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.gotcha.service.GotchaDeviceAdminReceiver
import com.gotcha.tools.HealthPermissionState
-import com.gotcha.tools.HealthTool
import com.gotcha.tools.TermuxTool
import com.gotcha.tools.ToolResult
+import com.gotcha.tools.healthConnectPermissionIntent
+import com.gotcha.ui.theme.SkinAlertDialog
import android.provider.Settings as AndroidSettings
@Composable
@@ -154,6 +153,8 @@ private fun PermissionRow(
onOpenDetails: (() -> Unit)? = null
) {
val context = LocalContext.current
+ val isHealthConnect = item.specialMarker == ToolResult.HEALTH_CONNECT
+ var showHealthConnectDialog by remember { mutableStateOf(false) }
Row(
modifier = Modifier
@@ -188,7 +189,15 @@ private fun PermissionRow(
if (item.androidPermission != null) {
onRequestRuntime((listOf(item.androidPermission) + item.extraPermissions).toTypedArray())
} else if (item.specialMarker != null) {
- openSpecialAccess(context, item.specialMarker, packageName)
+ // Health Connect cannot be granted from the standard
+ // runtime flow, and on some OEM builds the permission
+ // screen opens and closes with no visible result — so
+ // the toggle first explains where to go, then opens it.
+ if (isHealthConnect) {
+ showHealthConnectDialog = true
+ } else {
+ openSpecialAccess(context, item.specialMarker, packageName)
+ }
}
} else {
Toast.makeText(
@@ -200,6 +209,31 @@ private fun PermissionRow(
}
)
}
+
+ if (showHealthConnectDialog) {
+ SkinAlertDialog(
+ onDismissRequest = { showHealthConnectDialog = false },
+ title = { Text("Health Connect permission needed") },
+ text = {
+ Text(
+ "Gotcha can't read your health data yet. Open Health Connect, " +
+ "find Gotcha under App permissions, and allow the data types " +
+ "you're comfortable sharing, then return here."
+ )
+ },
+ confirmButton = {
+ TextButton(
+ onClick = {
+ showHealthConnectDialog = false
+ openSpecialAccess(context, ToolResult.HEALTH_CONNECT, packageName)
+ }
+ ) { Text("Open Health Connect") }
+ },
+ dismissButton = {
+ TextButton(onClick = { showHealthConnectDialog = false }) { Text("Not now") }
+ }
+ )
+ }
}
/**
@@ -244,20 +278,10 @@ internal fun openSpecialAccess(
`package` = it.`package`
}
}
- ToolResult.HEALTH_CONNECT -> {
- if (HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE) {
- PermissionController.createRequestPermissionResultContract()
- .createIntent(context, HealthTool.PERMISSIONS)
- } else {
- // No provider (or one that is out of date): steer to the Play listing instead of
- // crash-launching a screen nothing can handle — same journey as the agent path in
- // MainActivity.requestHealthConnect.
- Intent(
- Intent.ACTION_VIEW,
- Uri.parse("market://details?id=com.google.android.apps.healthdata")
- )
- }
- }
+ // Resolves the SDK's permission screen, or a fallback that actually
+ // exists on this device, so the toggle can never crash the app with an
+ // ActivityNotFoundException (see healthConnectPermissionIntent).
+ ToolResult.HEALTH_CONNECT -> healthConnectPermissionIntent(context)
// Only the Termux half of the journey: this path has no Activity to request the runtime
// permission from, and the allow-external-apps property can only be set inside Termux.
// MainActivity.requestTermuxAccess handles both halves when the agent asks.
@@ -266,7 +290,9 @@ internal fun openSpecialAccess(
}
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- context.startActivity(intent)
+ // A routing mistake or an OEM quirk must surface as a silent no-op, never
+ // a crash — the settings toggle should degrade, not take the app down.
+ runCatching { context.startActivity(intent) }
}
return intent
}
diff --git a/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt b/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt
index 5795ab1..5776e67 100644
--- a/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt
+++ b/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt
@@ -1,11 +1,14 @@
package com.gotcha.ui
import android.content.Context
+import android.content.Intent
import androidx.health.connect.client.PermissionController
import androidx.test.core.app.ApplicationProvider
import com.gotcha.tools.HealthPermissionState
import com.gotcha.tools.HealthTool
import com.gotcha.tools.ToolResult
+import com.gotcha.tools.healthConnectManagePermissionsIntent
+import com.gotcha.tools.healthConnectPermissionIntent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -82,4 +85,29 @@ class PermissionsRoutingTest {
// path added to PermissionsSection must not throw on such devices.
assertFalse(HealthPermissionState.refresh(context))
}
+
+ @Test
+ fun healthConnectManagePermissionsIntentTargetsThisApp() {
+ // The Android 14+ per-app permission manager, which OEM controllers
+ // register even when the SDK's RequestMultiplePermissions screen is not
+ // resolvable. Must name the app whose permissions are being managed.
+ val intent = healthConnectManagePermissionsIntent(context)
+ assertEquals(
+ "android.health.connect.action.MANAGE_HEALTH_PERMISSIONS",
+ intent.action
+ )
+ assertEquals(context.packageName, intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME))
+ }
+
+ @Test
+ fun healthConnectPermissionIntentSteersToPlayListingWhenProviderAbsent() {
+ // No Health Connect provider under Robolectric: the helper must pick the
+ // Play listing, not crash or fire an intent nothing can handle.
+ val intent = healthConnectPermissionIntent(context)
+ assertNotNull("there must always be a steer, never a crash", intent)
+ assertEquals(
+ "market://details?id=com.google.android.apps.healthdata",
+ intent?.getData()?.toString()
+ )
+ }
}