health: gate Health Connect on SDK status to fix launch crash (#891)
- Commit
e6e870aed989de56e1fe3e441a2bfea3885e0597- Author
- Vayun Mathur <[email protected]>
- When
- 2026-10-31 17:30 UTC (1 month ago)
- Parents
3a688ed
Symptom: the app crashed immediately on launch on Android 12 and 13, before any permission screen, while Android 14+ worked. Clearing storage did not help, matching a crash in startup code rather than in persisted state. Root cause: on API 33 and below Health Connect is a separate APK (com.google.android.apps.healthdata) instead of part of the OS, and HealthConnectClient.getOrCreate() throws when the provider is missing or too old. MainActivity.onCreateBeforeContent() called it unconditionally, so the process died before composition. The same unguarded call existed in HealthSyncWorker, the manifest <queries> block hid the provider from the status check under package-visibility rules, PersonalHealthRecords.upsert() assumed a client existed, and HealthAPI assumed init() had always provided one. Fix: a new HealthConnectSetup probe maps getSdkStatus() onto AVAILABLE / NOT_INSTALLED / UPDATE_REQUIRED and builds the Play Store installer intent. When the provider is unusable the app now shows a blocking setup screen explaining that Health Connect must be installed or updated, with a button opening the store listing and an automatic re-check on every resume, so returning from the install clears the screen with no relaunch. Startup, the sync worker and the PHR mirror all degrade to local-only Room mode instead of crashing, and the manifest now declares the provider package in <queries>. Alternatives rejected: merely catching around getOrCreate() would leave the app behind a permission gate whose Grant button has no provider to answer it. Auto-redirecting to the store with no explanation, or silently continuing offline while sync never happens, would both confuse more than a plain warning screen. User-visible effect: on Android 12/13 without (or with an outdated) Health Connect the app shows the installer screen instead of crashing; everywhere else behavior is unchanged. Verification: :health:compileDevKotlin and :health:testDevUnitTest pass (95 tests, 6 new in HealthConnectSetupTest); Android lint reports no errors and the only detekt errors are pre-existing ones in files this change does not touch. Still needs on-device testing on an API 31-33 device without Health Connect (screen appears, button opens the store, resume clears it), with an outdated provider (update variant), and a regression pass on API 34+.
Diff
health/src/main/AndroidManifest.xml
diff --git a/health/src/main/AndroidManifest.xml b/health/src/main/AndroidManifest.xmlindex 7fad1a36d7..d519aab16f 100644--- a/health/src/main/AndroidManifest.xml+++ b/health/src/main/AndroidManifest.xml@@ -84,6 +84,9 @@ <queries> <package android:name="com.vayunmathur.openassistant" />+ <!-- Health Connect's APK provider on API 33 and below. Without this, package-visibility+ rules hide the provider and getSdkStatus() cannot see it. -->+ <package android:name="com.google.android.apps.healthdata" /> </queries> <application
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 2a50034752..18cba166ed 100644--- a/health/src/main/java/com/vayunmathur/health/MainActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/MainActivity.kt@@ -8,11 +8,19 @@ import com.vayunmathur.library.ui.IconFavorite import com.vayunmathur.library.ui.IconFire import com.vayunmathur.library.ui.MaActivity import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+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.health.connect.client.permission.HealthPermission+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord import androidx.health.connect.client.records.BasalMetabolicRateRecord import androidx.health.connect.client.records.BloodGlucoseRecord@@ -45,6 +53,8 @@ import com.vayunmathur.library.util.MorphPage import com.vayunmathur.library.util.NavKey import com.vayunmathur.health.data.HealthRepository import com.vayunmathur.health.data.ReferenceCatalog+import com.vayunmathur.health.platform.HealthConnectAvailability+import com.vayunmathur.health.platform.HealthConnectSetup import com.vayunmathur.health.platform.MedicalViewModel import com.vayunmathur.health.platform.MedicalViewModelFactory import com.vayunmathur.health.platform.PersonalHealthRecords@@ -57,6 +67,7 @@ import com.vayunmathur.health.ui.BarChartDetails import com.vayunmathur.health.ui.BodyPage import com.vayunmathur.health.ui.CatalogPickerPage import com.vayunmathur.health.ui.ExerciseDetailsPage+import com.vayunmathur.health.ui.HealthConnectRequiredPage import com.vayunmathur.health.ui.HealthMetricConfig import com.vayunmathur.health.ui.MedicalPage @@ -152,20 +163,72 @@ class MainActivity : MaActivity() { } private lateinit var healthConnectClient: HealthConnectClient - override fun onCreateBeforeContent() {- healthConnectClient = HealthConnectClient.getOrCreate(this)+ /**+ * Creates the Health Connect client when the provider is usable, wiring it into HealthAPI+ * and PersonalHealthRecords.+ *+ * Idempotent: called from `onCreateBeforeContent` and again on every resume, because the+ * user can install the provider while this activity is alive. When the provider is missing+ * or too old this leaves HealthAPI in local-only mode and PersonalHealthRecords+ * uninitialised (its `isAvailable` reports false with no client).+ */+ private fun ensureHealthConnect() {+ if (HealthConnectSetup.current(this) != HealthConnectAvailability.AVAILABLE) {+ HealthAPI.initLocal(this, HealthRepository.get(this))+ return+ }+ if (!::healthConnectClient.isInitialized) {+ healthConnectClient = HealthConnectClient.getOrCreate(this)+ } val repository = HealthRepository.get(this) HealthAPI.init(healthConnectClient, this, repository)+ PersonalHealthRecords.init(this, healthConnectClient)+ }++ override fun onCreateBeforeContent() {+ // Health Connect is a separate APK on API 33 and below and getOrCreate throws when it is+ // missing or too old, which crashed launch outright. Its setup is gated on the SDK status;+ // Room, the food database and the reference catalog work without it, and the composable+ // below shows the install screen instead of the app until it is usable.+ ensureHealthConnect() FoodDatabase.init(this) ReferenceCatalog.init(this) // Unpacking is half a second of decompression and disk write. Do it now, in the background, // rather than the first time the user opens a picker and waits for it. ReferenceCatalog.warmUp(lifecycleScope)- PersonalHealthRecords.init(this, healthConnectClient) } @Composable override fun Content() {+ // Re-checked on every resume: returning from the Play Store install clears this screen+ // without a relaunch. The status call is a cached PackageManager lookup, not IPC.+ var availability by remember {+ mutableStateOf(HealthConnectSetup.current(this@MainActivity))+ }+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) {+ // The user may be returning from the Play Store install. Set up the client+ // first so the gate and the screens below never see an uninitialised one.+ ensureHealthConnect()+ availability = HealthConnectSetup.current(this@MainActivity)+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }++ if (availability != HealthConnectAvailability.AVAILABLE) {+ // Health Connect missing or too old: show the installer screen instead of the app.+ // Composing the permission gate here would launch its own getOrCreate probe and,+ // worse, a Grant button whose contract has no provider to answer it.+ HealthConnectRequiredPage(availability) {+ HealthConnectSetup.openInstaller(this@MainActivity)+ }+ return+ }+ val requestMedicalPermissions = rememberLauncherForActivityResult( contract = PermissionController.createRequestPermissionResultContract(), onResult = { /* Refusal is fine — the medical screens fall back to local data. */ }@@ -193,6 +256,7 @@ class MainActivity : MaActivity() { // devices cannot grant; the medical screens work from Room without it. LaunchedEffect(Unit) { if (PersonalHealthRecords.isAvailable() &&+ ::healthConnectClient.isInitialized && !healthConnectClient.permissionController.getGrantedPermissions() .containsAll(PersonalHealthRecords.PERMISSIONS) ) {
health/src/main/java/com/vayunmathur/health/platform/HealthConnectAvailability.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthConnectAvailability.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthConnectAvailability.ktnew file mode 100644index 0000000000..cee3098f9f--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthConnectAvailability.kt@@ -0,0 +1,100 @@+package com.vayunmathur.health.platform++import android.content.ActivityNotFoundException+import android.content.Context+import android.content.Intent+import androidx.core.net.toUri+import androidx.health.connect.client.HealthConnectClient+import com.vayunmathur.library.log.Log++/**+ * Whether Health Connect can be used on this device right now.+ *+ * On Android 14 and later Health Connect is part of the OS, so this is almost always+ * [AVAILABLE]. On Android 13 and below it is a separate APK (`com.google.android.apps.healthdata`)+ * the user must install from the Play Store; when it is missing or outdated+ * [HealthConnectClient.getOrCreate] throws instead of returning a client, which is what crashed+ * the app on launch — before any permission screen — on those releases. Every entry point that+ * touches Health Connect checks this first and shows the install screen instead.+ */+enum class HealthConnectAvailability {+ /** Usable: a client can be created and permissions can be requested. */+ AVAILABLE,++ /** The provider APK is missing: the user must install it. */+ NOT_INSTALLED,++ /** The provider APK is present but too old: the user must update it. */+ UPDATE_REQUIRED,+}++/**+ * Gates Health Connect access on the SDK status and builds the Play Store route for when it is+ * missing.+ *+ * The install URL is the `market://...&url=healthconnect%3A%2F%2Fonboarding` form from the Health+ * Connect onboarding docs: the store opens directly on the Health Connect listing. The `https://`+ * form is the fallback for devices with no store handler.+ */+object HealthConnectSetup {+ private const val TAG = "HealthConnectSetup"++ /** The APK provider's package on Android 13 and below. Also declared in `<queries>`. */+ const val PROVIDER_PACKAGE = "com.google.android.apps.healthdata"++ /** Play Store listing, opening directly on the Health Connect onboarding flow. */+ const val MARKET_URL =+ "market://details?id=com.google.android.apps.healthdata&url=healthconnect%3A%2F%2Fonboarding"++ /** The same listing as a web URL, for devices with no store handler. */+ const val WEB_URL =+ "https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata"++ /**+ * The current availability. Never throws: an SDK that cannot even report its status is+ * treated as missing, which is the state that used to crash launch.+ */+ // Broad catch is deliberate: this is the availability probe whose contract is to never+ // throw, and the client throws undocumented RuntimeExceptions when the provider is broken.+ @Suppress("TooGenericExceptionCaught")+ fun current(context: Context): HealthConnectAvailability {+ val status = try {+ HealthConnectClient.getSdkStatus(context)+ } catch (e: Exception) {+ Log.status(TAG, "Health Connect status check failed; treating as not installed", e)+ return HealthConnectAvailability.NOT_INSTALLED+ }+ return toAvailability(status)+ }++ /** Maps a [HealthConnectClient.getSdkStatus] result onto [HealthConnectAvailability]. */+ fun toAvailability(sdkStatus: Int): HealthConnectAvailability = when (sdkStatus) {+ HealthConnectClient.SDK_AVAILABLE -> HealthConnectAvailability.AVAILABLE+ HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED ->+ HealthConnectAvailability.UPDATE_REQUIRED+ // SDK_UNAVAILABLE covers a missing provider, an unsupported device, and anything new.+ else -> HealthConnectAvailability.NOT_INSTALLED+ }++ /**+ * Opens the Play Store (or a browser fallback) on the provider listing. Returns false when+ * nothing on the device handles either URL, so the caller can say so instead of crashing.+ */+ fun openInstaller(context: Context): Boolean {+ for (url in listOf(MARKET_URL, WEB_URL)) {+ try {+ context.startActivity(+ Intent(Intent.ACTION_VIEW, url.toUri())+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ )+ return true+ } catch (_: ActivityNotFoundException) {+ // No handler for this URL form; try the next one.+ } catch (e: SecurityException) {+ Log.status(TAG, "Not allowed to open the Health Connect installer", e)+ return false+ }+ }+ return false+ }+}
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 86d9128084..b4e9267fc8 100644--- a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt@@ -184,14 +184,19 @@ object PersonalHealthRecords { /** Writes one FHIR resource, returning its Health Connect id or null if the write did not land. */ // Broad catch is deliberate: a rejected resource must not cost the user the entry they // just typed, so failures are logged and swallowed and the row stays queued for retry.+ // The null return also covers Health Connect being unavailable (client never initialised),+ // which delete/readAll/dataSourceId already degrade on but this path previously assumed away. @Suppress("TooGenericExceptionCaught")- suspend fun upsert(dataSourceId: String, data: String): String? = try {- hc.upsertMedicalResources(- listOf(UpsertMedicalResourceRequest(dataSourceId, FHIR_VERSION, data))- ).firstOrNull()?.id?.fhirResourceId- } catch (e: Exception) {- Log.error(TAG, "Could not write a medical resource", e)- null+ suspend fun upsert(dataSourceId: String, data: String): String? {+ if (!isAvailable()) return null+ return try {+ hc.upsertMedicalResources(+ listOf(UpsertMedicalResourceRequest(dataSourceId, FHIR_VERSION, data))+ ).firstOrNull()?.id?.fhirResourceId+ } catch (e: Exception) {+ Log.error(TAG, "Could not write a medical resource", e)+ null+ } } /** Deletes one of this app's resources, returning whether Health Connect confirmed it. */
health/src/main/java/com/vayunmathur/health/ui/HealthConnectRequiredPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/HealthConnectRequiredPage.kt b/health/src/main/java/com/vayunmathur/health/ui/HealthConnectRequiredPage.ktnew file mode 100644index 0000000000..52232c550f--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/HealthConnectRequiredPage.kt@@ -0,0 +1,74 @@+package com.vayunmathur.health.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.health.R+import com.vayunmathur.health.platform.HealthConnectAvailability+import com.vayunmathur.library.ui.IconHealth+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SetupAction+import com.vayunmathur.library.ui.SetupScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * The blocking setup step shown when Health Connect is missing or too old to use.+ *+ * On Android 14 and later Health Connect is part of the OS, but on 13 and below it is a+ * separate APK the user must install — and `HealthConnectClient.getOrCreate` throws when it is+ * absent, which crashed the app on launch before any permission screen. So this renders instead+ * of the whole app (permissions gate included) until the provider is usable, explains what to+ * install, and sends the user to the Play Store listing. Returning from the store re-checks+ * automatically via the resume probe in `MainActivity`; nothing here needs a result callback.+ *+ * [onInstall] opens the store listing and reports whether anything handled it. When nothing+ * does — no store, no browser — the failure stays on this screen as text rather than a toast,+ * since there is no navigation host behind it to carry a snackbar.+ */+@Composable+fun HealthConnectRequiredPage(+ availability: HealthConnectAvailability,+ onInstall: () -> Boolean,+) {+ var installFailed by rememberSaveable { mutableStateOf(false) }+ val updating = availability == HealthConnectAvailability.UPDATE_REQUIRED+ SetupScaffold(+ title = stringResource(+ if (updating) R.string.health_connect_update_title+ else R.string.health_connect_required_title+ ),+ subtitle = stringResource(+ if (updating) R.string.health_connect_update_subtitle+ else R.string.health_connect_required_subtitle+ ),+ icon = { IconHealth() },+ primaryAction = SetupAction(+ stringResource(+ if (updating) R.string.health_connect_update_action+ else R.string.health_connect_install_action+ ),+ onClick = { installFailed = !onInstall() },+ ),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ Text(+ stringResource(+ if (updating) R.string.health_connect_update_body+ else R.string.health_connect_required_body+ ),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ if (installFailed) {+ Text(+ stringResource(R.string.health_connect_install_failed),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.error,+ )+ }+ }+}
health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/util/HealthAPI.ktindex 4e1e01790b..9f9aa7a773 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt@@ -34,7 +34,7 @@ import kotlinx.datetime.minus import kotlinx.datetime.plus object HealthAPI {- lateinit var healthConnectClient: HealthConnectClient+ private var healthConnectClient: HealthConnectClient? = null lateinit var preferences: SharedPreferences private var repository: HealthRepository? = null@@ -48,6 +48,17 @@ object HealthAPI { preferences = context.getSharedPreferences("sync", Context.MODE_PRIVATE) } + /**+ * Local-only mode for when Health Connect is missing or too old (API 33 and below without+ * the provider APK installed): Room and preferences work, the Health Connect mirror calls+ * below skip their remote half. Replaced by [init] once the provider is usable.+ */+ fun initLocal(context: Context, repository: HealthRepository) {+ this.healthConnectClient = null+ this.repository = repository+ preferences = context.getSharedPreferences("sync", Context.MODE_PRIVATE)+ }+ private fun repo(): HealthRepository = repository!! suspend fun lastRecord(recordType: RecordType): Record? {@@ -62,6 +73,8 @@ object HealthAPI { // Delete from local Room DB repo().deleteByIds(listOf(record.id)) + // Local-only mode (Health Connect missing or too old): nothing remote to delete.+ val client = healthConnectClient ?: return // Delete from Health Connect if it has a valid ID try { val recordClass: KClass<out androidx.health.connect.client.records.Record>? = when (record.type) {@@ -76,7 +89,7 @@ object HealthAPI { else -> null } if (recordClass != null) {- healthConnectClient.deleteRecords(+ client.deleteRecords( recordType = recordClass, recordIdsList = listOf(record.id), clientRecordIdsList = listOf(record.id)@@ -113,7 +126,9 @@ object HealthAPI { } try {- val response = healthConnectClient.insertRecords(listOf(hcRecord))+ // Local-only mode (Health Connect missing or too old): the row just written to Room+ // above stays the source of truth and there is nothing to mirror into.+ val response = healthConnectClient?.insertRecords(listOf(hcRecord)) ?: return val newId = response.recordIdsList.firstOrNull() if (newId != null) { Log.status("HealthAPI", "Successfully wrote record to Health Connect with ID: $newId")
health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.ktindex 2dbd659ae1..2e2f1434eb 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt@@ -48,6 +48,8 @@ import com.vayunmathur.health.CLASSES import com.vayunmathur.health.data.HealthRepository import com.vayunmathur.health.data.Record import com.vayunmathur.health.data.RecordType+import com.vayunmathur.health.platform.HealthConnectAvailability+import com.vayunmathur.health.platform.HealthConnectSetup import com.vayunmathur.library.util.DataStoreUtils import java.time.Duration import java.time.Instant@@ -79,6 +81,13 @@ class HealthSyncWorker( } private suspend fun sync() {+ // No provider, no sync: getOrCreate throws when Health Connect is missing or too old+ // (API 33 and below without the APK), which used to fail every run. Succeed quietly —+ // Room stays the source of truth and the next periodic run retries once it is installed.+ if (HealthConnectSetup.current(applicationContext) != HealthConnectAvailability.AVAILABLE) {+ Log.status(TAG, "Health Connect is not available; skipping sync")+ return+ } val healthConnectClient = HealthConnectClient.getOrCreate(applicationContext) val repository = HealthRepository.get(applicationContext) val ds = DataStoreUtils.getInstance(applicationContext)
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 966c77f5be..8bfd850585 100644--- a/health/src/main/res/values/strings.xml+++ b/health/src/main/res/values/strings.xml@@ -7,6 +7,25 @@ <!-- Permission wall: explains why Health Connect access is needed. Sentence --> <string name="grant_permissions_rationale">This app reads and writes your health data through Health Connect. Nothing leaves your device.</string> + <!-- HealthConnectRequiredPage: Setup title when the provider APK is missing. Noun phrase -->+ <string name="health_connect_required_title">Health Connect is required</string>+ <!-- HealthConnectRequiredPage: Setup subtitle when the provider APK is missing. Sentence -->+ <string name="health_connect_required_subtitle">This app stores and reads your health data through Health Connect, which isn\u2019t installed on this device yet.</string>+ <!-- HealthConnectRequiredPage: Setup body when the provider APK is missing. Sentences -->+ <string name="health_connect_required_body">On this Android version Health Connect is a separate app you install from the Play Store — it\u2019s free and made by Google. Install it, then come back here and this screen will clear on its own. Your medical records stay in this app either way.</string>+ <!-- HealthConnectRequiredPage: Install button when the provider APK is missing. Verb phrase -->+ <string name="health_connect_install_action">Install Health Connect</string>+ <!-- HealthConnectRequiredPage: Setup title when the provider APK is present but too old. Noun phrase -->+ <string name="health_connect_update_title">Health Connect needs updating</string>+ <!-- HealthConnectRequiredPage: Setup subtitle when the provider APK is too old. Sentence -->+ <string name="health_connect_update_subtitle">The Health Connect app on this device is too old for this version of Health.</string>+ <!-- HealthConnectRequiredPage: Setup body when the provider APK is too old. Sentences -->+ <string name="health_connect_update_body">Update Health Connect from the Play Store, then come back here and this screen will clear on its own. Your medical records stay in this app either way.</string>+ <!-- HealthConnectRequiredPage: Update button when the provider APK is too old. Verb phrase -->+ <string name="health_connect_update_action">Update Health Connect</string>+ <!-- HealthConnectRequiredPage: Shown when no app handles the store link. Sentence -->+ <string name="health_connect_install_failed">Couldn\u2019t open the Play Store. Install or update the \u201cHealth Connect\u201d app by Google manually, then return here.</string>+ <!-- BarChartDetails: SecondaryTabRow tab for daily aggregation view. Noun --> <string name="tab_day">Day</string> <!-- BarChartDetails: Tab for weekly aggregation. Noun -->
health/src/test/java/com/vayunmathur/health/platform/HealthConnectSetupTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/platform/HealthConnectSetupTest.kt b/health/src/test/java/com/vayunmathur/health/platform/HealthConnectSetupTest.ktnew file mode 100644index 0000000000..f492f31ef7--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/platform/HealthConnectSetupTest.kt@@ -0,0 +1,65 @@+package com.vayunmathur.health.platform++import androidx.health.connect.client.HealthConnectClient+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Regression test for #891: the app crashed on launch on Android 12/13 because nothing checked+ * the Health Connect SDK status before calling `getOrCreate`. [HealthConnectSetup] now gates+ * every entry point; this pins the status mapping (including unknown future codes degrading to+ * not-installed rather than crashing) and the installer URLs.+ */+class HealthConnectSetupTest {++ @Test+ fun availableMapsToAvailable() {+ assertEquals(+ HealthConnectAvailability.AVAILABLE,+ HealthConnectSetup.toAvailability(HealthConnectClient.SDK_AVAILABLE),+ )+ }++ @Test+ fun updateRequiredMapsToUpdateRequired() {+ assertEquals(+ HealthConnectAvailability.UPDATE_REQUIRED,+ HealthConnectSetup.toAvailability(+ HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED+ ),+ )+ }++ @Test+ fun unavailableMapsToNotInstalled() {+ assertEquals(+ HealthConnectAvailability.NOT_INSTALLED,+ HealthConnectSetup.toAvailability(HealthConnectClient.SDK_UNAVAILABLE),+ )+ }++ @Test+ fun unknownFutureStatusMapsToNotInstalledRatherThanCrashing() {+ assertEquals(+ HealthConnectAvailability.NOT_INSTALLED,+ HealthConnectSetup.toAvailability(Int.MAX_VALUE),+ )+ }++ @Test+ fun marketUrlTargetsTheProviderPackageWithOnboarding() {+ assertTrue(+ HealthConnectSetup.MARKET_URL.startsWith(+ "market://details?id=${HealthConnectSetup.PROVIDER_PACKAGE}"+ )+ )+ assertTrue(HealthConnectSetup.MARKET_URL.contains("healthconnect"))+ }++ @Test+ fun webFallbackTargetsTheSameProviderPackage() {+ assertTrue(HealthConnectSetup.WEB_URL.startsWith("https://"))+ assertTrue(HealthConnectSetup.WEB_URL.contains("id=${HealthConnectSetup.PROVIDER_PACKAGE}"))+ }+}