emergency: fix all lint findings
- Commit
8c9515a02ee306dfe472cace4f407b93b9da3e6c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 05:04 UTC (19 days ago)
- Parents
322ad42
Fix every lint warning reported for the emergency module's own sources by :emergency:lintDev, now 0 errors / 0 warnings for emergency/** (remaining report entries are transitive library findings owned by other clusters).
StaticFieldLeak: EmergencyRepository no longer stores a Context — the singleton derives its non-Context collaborators once in create() (device-protected SharedPreferences, ContactReader over ContentResolver+Resources, UserManager, PackageManager, packageName), and ContactReader no longer takes a Context (14 test call sites updated). MissingPermission: EmergencyNumberLookup now catches SecurityException explicitly and degrades to the 112 fallback. PackageStructure: SosActionReceiver moved receiver/ to notifications/ (manifest name + imports + tests) and SosNavigation split out of Navigation.kt into ui/; OneComposablePerFile also split EditInfoPage out. Manifest: removed the silently-ignored directBootAware attributes from both activity-alias entries, removed MainActivity's redundant label, added the optional telephony uses-feature for the ChromeOS hardware check. LocalContextResourcesRead: integerResource() in SosScreen. UseKtx: toUri() x2 and SharedPreferences.edit {}. UnusedResources: deleted five verified-unused strings.
One justified suppression: tools:ignore ProtectedPermissions on START_ACTIVITIES_FROM_BACKGROUND — a signature|preinstalled permission, matching the manifest's existing ignores for CALL_PRIVILEGED/MANAGE_USERS. No lint config or baseline changed.
Verified: ./gradlew :emergency:lintDev (0 own-module errors/warnings) and :emergency:testDevUnitTest green.Diff
emergency/src/main/AndroidManifest.xml
diff --git a/emergency/src/main/AndroidManifest.xml b/emergency/src/main/AndroidManifest.xmlindex 2628247f25..96cd1fdaec 100644--- a/emergency/src/main/AndroidManifest.xml+++ b/emergency/src/main/AndroidManifest.xml@@ -31,13 +31,16 @@ <uses-permission android:name="android.permission.VIBRATE" /> <!-- The SOS receiver fires the call broadcast from the background alarm. -->- <uses-permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND" />+ <uses-permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND"+ tools:ignore="ProtectedPermissions" /> <!-- The SOS countdown runs as a foreground service with its notification. --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <!-- specialUse foreground subtype for the SOS countdown service. --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" /> <!-- Reads the SIM emergency-number list so the SOS screen names the real number. --> <uses-permission android:name="android.permission.READ_PHONE_STATE" />+ <!-- Telephony is optional hardware (e.g. ChromeOS tablets); the SOS flow degrades to the 112 fallback without it. -->+ <uses-feature android:name="android.hardware.telephony" android:required="false" /> <!-- Privileged half of emergency-number lookup. Inert without priv-app promotion. --> <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" tools:ignore="ProtectedPermissions" />@@ -109,7 +112,6 @@ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:directBootAware="true" android:exported="true"- android:label="@string/app_name" android:launchMode="singleTask" android:showWhenLocked="true" android:taskAffinity="com.android.settings"@@ -118,7 +120,6 @@ <!-- The lock-screen view card, answering EMERGENCY_ASSISTANCE. --> <activity-alias android:name=".ui.ViewInfoActivity"- android:directBootAware="true" android:exported="true" android:label="@string/app_name" android:targetActivity=".MainActivity">@@ -243,7 +244,6 @@ --> <activity-alias android:name=".ui.SosEntryPoint"- android:directBootAware="true" android:exported="true" android:label="@string/sos_channel_name" android:permission="android.permission.MANAGE_SENSOR_PRIVACY"@@ -277,7 +277,7 @@ both are explicit-class intents from our own notification, alarm and screen. --> <receiver- android:name=".receiver.SosActionReceiver"+ android:name=".notifications.SosActionReceiver" android:exported="false"> <intent-filter> <action android:name="com.vayunmathur.emergency.broadcast.MAKE_EMERGENCY_CALL" />
emergency/src/main/java/com/vayunmathur/emergency/Navigation.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/Navigation.kt b/emergency/src/main/java/com/vayunmathur/emergency/Navigation.ktindex 91cfea95ba..f0751e2f3d 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/Navigation.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/Navigation.kt@@ -5,12 +5,9 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.emergency.platform.EmergencyViewModel-import com.vayunmathur.emergency.platform.SosCoordinator import com.vayunmathur.emergency.ui.EditInfoPage-import com.vayunmathur.emergency.ui.SosScreen import com.vayunmathur.emergency.ui.ViewInfoScreen import com.vayunmathur.library.util.DetailPage-import com.vayunmathur.library.util.FullscreenPage import com.vayunmathur.library.util.ListPage import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack@@ -19,7 +16,7 @@ import com.vayunmathur.library.util.rememberNavBackStack * Navigation host for the info surfaces: view and edit. * * The SOS countdown is not hosted here: it keeps its own activity (see- * SosActivity in the manifest) and renders through [SosNavigation], so the+ * SosActivity in the manifest) and renders through [com.vayunmathur.emergency.ui.SosNavigation], so the * shared graph has all three destinations without the countdown inheriting * this host's task or the host inheriting the countdown's lock-screen, * single-instance, no-history semantics.@@ -58,14 +55,3 @@ fun Navigation( } } -/** The one-destination SOS host inside SosActivity. */-@Composable-fun SosNavigation(coordinator: SosCoordinator) {- val backStack = rememberNavBackStack<Route>(Route.Sos)- MainNavigation(backStack) {- entry<Route.Sos>(metadata = FullscreenPage()) {- val state by coordinator.state.collectAsStateWithLifecycle()- SosScreen(state = state, actions = coordinator)- }- }-}
emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.ktindex 2f2484d85d..d313190488 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt@@ -2,6 +2,7 @@ package com.vayunmathur.emergency.data import android.graphics.Bitmap import android.net.Uri+import androidx.core.net.toUri /** * The owner's identity details plus their emergency contacts.@@ -92,5 +93,5 @@ fun serializeContacts(uris: List<Uri>): String = uris.joinToString(CONTACT_SEPAR fun parseContactUris(serialized: String): List<Uri> = serialized.split(CONTACT_SEPARATOR).mapNotNull { val trimmed = it.trim()- if (trimmed.isEmpty()) null else runCatching { Uri.parse(trimmed) }.getOrNull()+ if (trimmed.isEmpty()) null else runCatching { trimmed.toUri() }.getOrNull() }
emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.ktindex c829d63f59..9a87f23f76 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt@@ -30,14 +30,13 @@ private const val TAG = "EmergencyRepository" * the credential-encrypted contacts provider. Reads pre-unlock return whatever is already * stored without pruning. */-class EmergencyRepository private constructor(private val app: Context) {-- private val prefs: SharedPreferences by lazy {- // Device-protected storage so the lock-screen view can read post-reboot pre-unlock;- // contact URIs stored here are only *resolved* once unlocked (see load below).- val device = app.createDeviceProtectedStorageContext()- device.getSharedPreferences(PREFS, Context.MODE_PRIVATE)- }+class EmergencyRepository private constructor(+ private val prefs: SharedPreferences,+ private val contacts: ContactReader,+ private val userManager: UserManager?,+ private val packageManager: PackageManager,+ private val packageName: String,+) { private val mutable = MutableStateFlow(EmergencyInfo()) val info: StateFlow<EmergencyInfo> = mutable.asStateFlow()@@ -77,8 +76,7 @@ class EmergencyRepository private constructor(private val app: Context) { /** Adds a contact URI after validating it still resolves; returns false when rejected. */ suspend fun addContact(phoneUri: Uri): Boolean = withContext(Dispatchers.IO) {- val reader = ContactReader(app)- val contact = reader.read(phoneUri) ?: return@withContext false+ val contact = contacts.read(phoneUri) ?: return@withContext false val current = mutable.value.contacts if (current.any { it.phoneUri == phoneUri }) return@withContext true persistUris(current.map { it.phoneUri } + phoneUri)@@ -107,7 +105,7 @@ class EmergencyRepository private constructor(private val app: Context) { val uris = parseContactUris(serialized) // Pre-unlock the contacts cannot be resolved; carry the URIs with blank snapshots. val contacts = if (isUnlocked()) {- ContactReader(app).readAll(uris)+ contacts.readAll(uris) } else { uris.map { EmergencyContact(it, "", "", "") } }@@ -127,7 +125,7 @@ class EmergencyRepository private constructor(private val app: Context) { */ private fun resolveAndPrune(info: EmergencyInfo): EmergencyInfo { val uris = info.contacts.map { it.phoneUri }- val resolved = ContactReader(app).readAll(uris)+ val resolved = contacts.readAll(uris) if (resolved.size != uris.size) { persistUris(resolved.map { it.phoneUri }) return info.copy(contacts = resolved)@@ -141,8 +139,7 @@ class EmergencyRepository private constructor(private val app: Context) { prefs.edit { putString(EmergencyKeys.CONTACTS, serializeContacts(uris)) } } - private fun isUnlocked(): Boolean =- app.getSystemService(UserManager::class.java)?.isUserUnlocked != false+ private fun isUnlocked(): Boolean = userManager?.isUserUnlocked != false /** * Disables the Settings first-run suggestion once anything is set, re-enables when the@@ -155,8 +152,8 @@ class EmergencyRepository private constructor(private val app: Context) { PackageManager.COMPONENT_ENABLED_STATE_ENABLED } runCatching {- app.packageManager.setComponentEnabledSetting(- ComponentName(app, SUGGESTION_CLASS),+ packageManager.setComponentEnabledSetting(+ ComponentName(packageName, SUGGESTION_CLASS), state, PackageManager.DONT_KILL_APP, )@@ -173,7 +170,25 @@ class EmergencyRepository private constructor(private val app: Context) { fun get(context: Context): EmergencyRepository = instance ?: synchronized(this) {- instance ?: EmergencyRepository(context.applicationContext).also { instance = it }+ instance ?: create(context.applicationContext).also { instance = it } }++ /**+ * Builds the singleton from non-Context collaborators derived from the application+ * context, so the static instance holds no [Context] (StaticFieldLeak): preferences,+ * the contacts reader's resolver/resources, and the two system services it needs.+ */+ private fun create(app: Context): EmergencyRepository {+ // Device-protected storage so the lock-screen view can read post-reboot pre-unlock;+ // contact URIs stored here are only *resolved* once unlocked (see load).+ val device = app.createDeviceProtectedStorageContext()+ return EmergencyRepository(+ prefs = device.getSharedPreferences(PREFS, Context.MODE_PRIVATE),+ contacts = ContactReader(app.contentResolver, app.resources),+ userManager = app.getSystemService(UserManager::class.java),+ packageManager = app.packageManager,+ packageName = app.packageName,+ )+ } } }
emergency/src/main/java/com/vayunmathur/emergency/notifications/SosActionReceiver.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.kt b/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosActionReceiver.ktsimilarity index 99%rename from emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.ktrename to emergency/src/main/java/com/vayunmathur/emergency/notifications/SosActionReceiver.ktindex 6163969041..89eaef7704 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosActionReceiver.kt@@ -1,4 +1,4 @@-package com.vayunmathur.emergency.receiver+package com.vayunmathur.emergency.notifications import android.app.AlarmManager import android.app.PendingIntent
emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt b/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.ktindex fb68e7906a..bf9eb8cd8d 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt@@ -8,7 +8,6 @@ import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import com.vayunmathur.emergency.R-import com.vayunmathur.emergency.receiver.SosActionReceiver /** * The SOS countdown notification.
emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.ktindex 0c646c7a99..f4d48b4ddc 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt@@ -1,7 +1,8 @@ package com.vayunmathur.emergency.platform +import android.content.ContentResolver import android.content.ContentUris-import android.content.Context+import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri@@ -20,12 +21,15 @@ private const val TAG = "EmergencyContactReader" * resolves so contacts deleted from the address book can be pruned. Needs `READ_CONTACTS` * (a normal runtime grant); without it every read returns null and the UI must prompt. */-class ContactReader(private val context: Context) {+class ContactReader(+ private val resolver: ContentResolver,+ private val resources: Resources,+) { /** Reads one contact, or null when the URI no longer resolves or access is denied. */ fun read(phoneUri: Uri): EmergencyContact? { val cursor = runCatching {- context.contentResolver.query(+ resolver.query( phoneUri, arrayOf( ContactsContract.Contacts.DISPLAY_NAME,@@ -46,7 +50,7 @@ class ContactReader(private val context: Context) { val number = it.getString(1).orEmpty() if (number.isBlank()) return null val type = ContactsContract.CommonDataKinds.Phone.getTypeLabel(- context.resources, it.getInt(2), it.getString(3),+ resources, it.getInt(2), it.getString(3), ).toString() val photo = readPhoto(it.getLong(4)) return EmergencyContact(phoneUri, name, number, type, photo)@@ -60,7 +64,7 @@ class ContactReader(private val context: Context) { fun isValid(phoneUri: Uri?): Boolean { if (phoneUri == null) return false val cursor = runCatching {- context.contentResolver.query(phoneUri, null, null, null, null)+ resolver.query(phoneUri, null, null, null, null) }.getOrElse { Log.status(TAG, "unable to validate contact $phoneUri", it) return false@@ -72,7 +76,7 @@ class ContactReader(private val context: Context) { if (photoId <= 0) return null val photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, photoId) val cursor = runCatching {- context.contentResolver.query(+ resolver.query( photoUri, arrayOf(ContactsContract.Contacts.Photo.PHOTO), null, null, null, ) }.getOrNull() ?: return null
emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.ktindex 6ea6bec2e4..ca3bcd8fac 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt@@ -42,10 +42,16 @@ class EmergencyNumberLookup(private val context: Context) { } if (!hasPhoneStateGrant()) return null val telecom = context.getSystemService<TelephonyManager>() ?: return null- val lists = runCatching {+ // getEmergencyNumberList needs READ_PRIVILEGED_PHONE_STATE on top of the+ // READ_PHONE_STATE grant checked above; without the privileged half the platform+ // throws SecurityException, which degrades to the fallback number like a missing grant.+ val lists = try { telecom.getEmergencyNumberList(EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_POLICE)- }.getOrElse {- Log.status(TAG, "could not read the emergency-number list", it)+ } catch (e: SecurityException) {+ Log.status(TAG, "no privileged grant for the emergency-number list", e)+ return null+ } catch (e: Exception) {+ Log.status(TAG, "could not read the emergency-number list", e) return null } if (lists.isNullOrEmpty()) return null
emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.ktindex 649d6afab3..23051e2dd4 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt@@ -1,6 +1,7 @@ package com.vayunmathur.emergency.platform import android.net.Uri+import androidx.core.net.toUri import com.vayunmathur.emergency.data.EmergencyContact import com.vayunmathur.emergency.data.EmergencyInfo import com.vayunmathur.emergency.data.ImportedAllergy@@ -125,7 +126,7 @@ interface SosActions { /** Preview/sample contact for screenshots. */ fun sampleContact(): EmergencyContact = EmergencyContact(- phoneUri = Uri.parse("content://com.android.contacts/data/1"),+ phoneUri = "content://com.android.contacts/data/1".toUri(), displayName = "Alex Rivera", phoneNumber = "(555) 010-2030", phoneType = "Mobile",
emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.ktindex 63a5ddc6c5..e1927c5a6f 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt@@ -9,6 +9,7 @@ import android.net.Uri import android.os.Bundle import android.os.SystemClock import android.provider.Settings+import androidx.core.content.edit import com.vayunmathur.library.log.Log private const val TAG = "EmergencyGestureProvider"@@ -44,9 +45,9 @@ class GestureProvider : ContentProvider() { ) } METHOD_SET_NUMBER_OVERRIDE -> {- prefs().edit()- .putString(EXTRA_CALL_NUMBER, extras?.getString(EXTRA_CALL_NUMBER))- .apply()+ prefs().edit {+ putString(EXTRA_CALL_NUMBER, extras?.getString(EXTRA_CALL_NUMBER))+ } // Stock notifies observers of the gesture authority URI here; Settings // registers a content observer on it, so without this the override row // never refreshes after a set. Both authorities served in the manifest,
emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.ktindex 637435d455..e2b53ee139 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt@@ -3,7 +3,7 @@ package com.vayunmathur.emergency.platform import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope-import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.notifications.SosActionReceiver import com.vayunmathur.emergency.service.SosCountdownService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow
emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt b/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.ktindex d906627c05..ce5feee885 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt@@ -16,7 +16,7 @@ import com.vayunmathur.emergency.notifications.SosNotifications import com.vayunmathur.emergency.platform.EmergencyNumberLookup import com.vayunmathur.emergency.platform.GestureProvider import com.vayunmathur.emergency.platform.SosSound-import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.notifications.SosActionReceiver import com.vayunmathur.emergency.ui.SosActivity private const val TAG = "EmergencySosService"
emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoPage.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoPage.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoPage.ktnew file mode 100644index 0000000000..eee8a130a3--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoPage.kt@@ -0,0 +1,106 @@+package com.vayunmathur.emergency.ui+import android.Manifest+import android.content.Intent+import android.provider.ContactsContract+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+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.unit.dp+import androidx.health.connect.client.PermissionController+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.emergency.R+import com.vayunmathur.emergency.data.BLOOD_TYPE_OPTIONS+import com.vayunmathur.emergency.data.ORGAN_DONOR_NO+import com.vayunmathur.emergency.data.ORGAN_DONOR_YES+import com.vayunmathur.emergency.platform.EmergencyActions+import com.vayunmathur.emergency.platform.EmergencyUiState+import com.vayunmathur.emergency.platform.EmergencyViewModel+import com.vayunmathur.emergency.platform.HealthConnectMedical+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.FormSection+import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.SettingsExposedSelectRow+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * Edits the owner's medical details and emergency contacts.+ *+ * Answers `android.settings.EDIT_EMERGENCY_INFO` like GrapheneOS's EditInfoActivity.+ * The owner's identity (name, and address when available) is picked from a contact+ * card with `ACTION_PICK` against `Contacts.CONTENT_URI` and snapshotted into+ * storage — never typed here. Emergency contacts are picked separately with+ * `ACTION_PICK` against `Phone.CONTENT_URI` so the stored value is the per-number+ * URI GrapheneOS persists (not the aggregate contact URI). Picking requires+ * `READ_CONTACTS`, requested here. Allergies and medications are never typed here -+ * they are read from Health Connect, which this screen only offers to connect.+ */+/** Binds the ViewModel to the stateless screen, owning the pick/permission launchers. */+@Composable+fun EditInfoPage(viewModel: EmergencyViewModel) {+ val state by viewModel.state.collectAsStateWithLifecycle()+ val pickContact = rememberLauncherForActivityResult(+ ActivityResultContracts.StartActivityForResult(),+ ) { result ->+ result.data?.data?.let { viewModel.addContact(it) }+ }+ val pickOwner = rememberLauncherForActivityResult(+ ActivityResultContracts.StartActivityForResult(),+ ) { result ->+ result.data?.data?.let { viewModel.pickOwner(it) }+ }+ val requestContacts = rememberLauncherForActivityResult(+ ActivityResultContracts.RequestPermission(),+ ) { granted ->+ if (granted) viewModel.refresh()+ }+ // Health Connect has its own permission contract, distinct from the runtime one above.+ // Refusal is fine - the card just keeps showing whatever is already granted.+ val requestHealth = rememberLauncherForActivityResult(+ PermissionController.createRequestPermissionResultContract(),+ ) { viewModel.refreshHealthConnect() }++ val gatePick = { open: () -> Unit ->+ if (state.hasContactsAccess) {+ open()+ } else {+ requestContacts.launch(Manifest.permission.READ_CONTACTS)+ }+ }+ EditInfoScreen(+ state = state,+ actions = viewModel,+ onPickContact = {+ gatePick {+ pickContact.launch(+ Intent(+ Intent.ACTION_PICK,+ ContactsContract.CommonDataKinds.Phone.CONTENT_URI,+ ),+ )+ }+ },+ onPickOwner = {+ gatePick {+ pickOwner.launch(+ Intent(+ Intent.ACTION_PICK,+ ContactsContract.Contacts.CONTENT_URI,+ ),+ )+ }+ },+ onConnectHealth = { requestHealth.launch(HealthConnectMedical.PERMISSIONS) },+ )+}
emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.ktindex a9e4282db0..9791ecbc31 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt@@ -35,76 +35,6 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior -/**- * Edits the owner's medical details and emergency contacts.- *- * Answers `android.settings.EDIT_EMERGENCY_INFO` like GrapheneOS's EditInfoActivity.- * The owner's identity (name, and address when available) is picked from a contact- * card with `ACTION_PICK` against `Contacts.CONTENT_URI` and snapshotted into- * storage — never typed here. Emergency contacts are picked separately with- * `ACTION_PICK` against `Phone.CONTENT_URI` so the stored value is the per-number- * URI GrapheneOS persists (not the aggregate contact URI). Picking requires- * `READ_CONTACTS`, requested here. Allergies and medications are never typed here -- * they are read from Health Connect, which this screen only offers to connect.- */-/** Binds the ViewModel to the stateless screen, owning the pick/permission launchers. */-@Composable-fun EditInfoPage(viewModel: EmergencyViewModel) {- val state by viewModel.state.collectAsStateWithLifecycle()- val pickContact = rememberLauncherForActivityResult(- ActivityResultContracts.StartActivityForResult(),- ) { result ->- result.data?.data?.let { viewModel.addContact(it) }- }- val pickOwner = rememberLauncherForActivityResult(- ActivityResultContracts.StartActivityForResult(),- ) { result ->- result.data?.data?.let { viewModel.pickOwner(it) }- }- val requestContacts = rememberLauncherForActivityResult(- ActivityResultContracts.RequestPermission(),- ) { granted ->- if (granted) viewModel.refresh()- }- // Health Connect has its own permission contract, distinct from the runtime one above.- // Refusal is fine - the card just keeps showing whatever is already granted.- val requestHealth = rememberLauncherForActivityResult(- PermissionController.createRequestPermissionResultContract(),- ) { viewModel.refreshHealthConnect() }-- val gatePick = { open: () -> Unit ->- if (state.hasContactsAccess) {- open()- } else {- requestContacts.launch(Manifest.permission.READ_CONTACTS)- }- }- EditInfoScreen(- state = state,- actions = viewModel,- onPickContact = {- gatePick {- pickContact.launch(- Intent(- Intent.ACTION_PICK,- ContactsContract.CommonDataKinds.Phone.CONTENT_URI,- ),- )- }- },- onPickOwner = {- gatePick {- pickOwner.launch(- Intent(- Intent.ACTION_PICK,- ContactsContract.Contacts.CONTENT_URI,- ),- )- }- },- onConnectHealth = { requestHealth.launch(HealthConnectMedical.PERMISSIONS) },- )-} /** The editor: picked identity, medical fields, a Health Connect prompt, contacts add/remove. */ @Composable
emergency/src/main/java/com/vayunmathur/emergency/ui/SosNavigation.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/SosNavigation.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/SosNavigation.ktnew file mode 100644index 0000000000..a4cad9fc7f--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/SosNavigation.kt@@ -0,0 +1,22 @@+package com.vayunmathur.emergency.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.emergency.Route+import com.vayunmathur.emergency.platform.SosCoordinator+import com.vayunmathur.library.util.FullscreenPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack++/** The one-destination SOS host inside SosActivity. */+@Composable+fun SosNavigation(coordinator: SosCoordinator) {+ val backStack = rememberNavBackStack<Route>(Route.Sos)+ MainNavigation(backStack) {+ entry<Route.Sos>(metadata = FullscreenPage()) {+ val state by coordinator.state.collectAsStateWithLifecycle()+ SosScreen(state = state, actions = coordinator)+ }+ }+}
emergency/src/main/java/com/vayunmathur/emergency/ui/SosScreen.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/SosScreen.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/SosScreen.ktindex 773af55071..18a2875085 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/ui/SosScreen.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/SosScreen.kt@@ -25,6 +25,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInspectionMode+import androidx.compose.ui.res.integerResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp@@ -34,7 +35,7 @@ import com.vayunmathur.emergency.R import com.vayunmathur.emergency.platform.SosActions import com.vayunmathur.emergency.platform.SosCoordinator import com.vayunmathur.emergency.platform.SosUiState-import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.notifications.SosActionReceiver import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.Text@@ -71,7 +72,7 @@ class SosActivity : ComponentActivity() { enableEdgeToEdge() setContent { DynamicTheme {- com.vayunmathur.emergency.SosNavigation(coordinator)+ SosNavigation(coordinator) } } }@@ -137,11 +138,12 @@ fun SosScreen(state: SosUiState, actions: SosActions) { // Screenshots render this screen with literal state; the countdown effect must not fire // there (no broadcast stack, no activity to finish). val inspection = LocalInspectionMode.current+ val sosTickMillis = integerResource(R.integer.sos_count_down_interval) // Firing the call exactly once when the clock hits zero. if (!inspection) { LaunchedEffect(state.totalMillis) {- val tick = context.resources.getInteger(R.integer.sos_count_down_interval).toLong()+ val tick = sosTickMillis.toLong() var left = state.totalMillis while (left > 0) { delay(tick.coerceAtMost(left))
emergency/src/main/res/values/strings.xml
diff --git a/emergency/src/main/res/values/strings.xml b/emergency/src/main/res/values/strings.xmlindex e9faaf3de6..b0e9d4fc3e 100644--- a/emergency/src/main/res/values/strings.xml+++ b/emergency/src/main/res/values/strings.xml@@ -10,10 +10,6 @@ <!-- Settings suggestion: explanation shown to first-run users. --> <string name="settings_suggestion_body">First responders can see it from the lock screen in an emergency.</string> - <!-- View screen: tab showing the owner's medical details. Noun. -->- <string name="tab_title_info">Info</string>- <!-- View screen: tab showing the emergency contacts. Noun. -->- <string name="tab_title_contacts">Contacts</string> <!-- View screen: heading above the owner's name and address cards. Noun. --> <string name="group_owner">Owner</string> <!-- View screen: heading above each emergency contact's name and number cards. Noun phrase. -->@@ -57,15 +53,11 @@ <string name="section_medical_info">Medical information</string> <!-- Contact row: button that removes the contact. Verb. --> <string name="remove_contact">Remove</string>- <!-- Contact row: button that opens the contact. Verb. -->- <string name="view_contact">View</string> <!-- Contacts permission: title of the prompt shown before the contact list. --> <string name="contacts_permission_title">Contacts access is off</string> <!-- Contacts permission: explanation shown before the contact list. --> <string name="contacts_permission_hint">Allow Emergency to read contacts to choose who to call for you.</string>- <!-- Contacts permission: button that requests the permission. Verb phrase. -->- <string name="contacts_permission_action">Allow contacts access</string> <!-- SOS: countdown subtitle naming the number about to be dialled. Has the number as its argument. --> <string name="sos_subtitle">Calling <xliff:g id="number" example="911">%1$s</xliff:g> in <xliff:g id="seconds" example="5">%2$d</xliff:g></string> <!-- SOS: slide-to-cancel control. Verb. -->@@ -84,8 +76,6 @@ <!-- View screen: heading above current medications read from Health Connect. Noun phrase. --> <string name="section_current_medications">Medications</string>- <!-- Attribution shown under the Health Connect sections. -->- <string name="from_health_connect">From Health Connect</string> <!-- Allergy criticality shown as a trailing label on high-severity allergies. Noun phrase. --> <string name="allergy_high">Severe</string> <!-- Allergy criticality shown as a trailing label on low-severity allergies. Noun. -->
emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.ktindex 899e59214f..c4aac682ed 100644--- a/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformExtraTest.kt@@ -51,15 +51,15 @@ class ReaderFailureModesTest { @Test fun `provider failures and null cursors degrade to null`() { FakeContactsProvider.failUris += phoneUri.toString()- assertNull(ContactReader(ctx).read(phoneUri))- assertFalse(ContactReader(ctx).isValid(phoneUri))+ assertNull(ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri))+ assertFalse(ContactReader(ctx.contentResolver, ctx.resources).isValid(phoneUri)) val rawUri = Uri.parse("content://com.android.contacts/raw_contacts/7") FakeContactsProvider.failUris += rawUri.toString() assertNull(OwnerIdentityReader(ctx).read(rawUri)) FakeContactsProvider.failUris.clear() FakeContactsProvider.nullUris += phoneUri.toString()- assertNull(ContactReader(ctx).read(phoneUri))- assertFalse(ContactReader(ctx).isValid(phoneUri))+ assertNull(ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri))+ assertFalse(ContactReader(ctx.contentResolver, ctx.resources).isValid(phoneUri)) } @Test
emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.ktindex cd55dfc709..fe555a4659 100644--- a/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/PlatformTests.kt@@ -53,7 +53,7 @@ class ContactReaderTest { fun `reads name number type and photo`() { FakeContactsProvider.phones[phoneUri.toString()] = FakeContactsProvider.PhoneRow("Alex Rivera", "(555) 010-2030", photoId = 9)- val contact = ContactReader(ctx).read(phoneUri)+ val contact = ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri) assertNotNull(contact) assertEquals("Alex Rivera", contact.displayName) assertEquals("(555) 010-2030", contact.phoneNumber)@@ -64,17 +64,17 @@ class ContactReaderTest { @Test fun `missing contact and blank number read as null`() {- assertNull(ContactReader(ctx).read(phoneUri))+ assertNull(ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri)) FakeContactsProvider.phones[phoneUri.toString()] = FakeContactsProvider.PhoneRow("No Number", " ")- assertNull(ContactReader(ctx).read(phoneUri))+ assertNull(ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri)) // custom type label is used when present FakeContactsProvider.phones[phoneUri.toString()] = FakeContactsProvider.PhoneRow( "Custom", "123", ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM, "Cabin", )- assertEquals("Cabin", ContactReader(ctx).read(phoneUri)?.phoneType)+ assertEquals("Cabin", ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri)?.phoneType) } @Test@@ -82,23 +82,23 @@ class ContactReaderTest { FakeContactsProvider.phones[phoneUri.toString()] = FakeContactsProvider.PhoneRow("Alex", "123") val dead = Uri.parse("content://com.android.contacts/data/phones/99")- val all = ContactReader(ctx).readAll(listOf(phoneUri, dead))+ val all = ContactReader(ctx.contentResolver, ctx.resources).readAll(listOf(phoneUri, dead)) assertEquals(1, all.size)- assertTrue(ContactReader(ctx).isValid(phoneUri))- assertFalse(ContactReader(ctx).isValid(dead))- assertFalse(ContactReader(ctx).isValid(null))+ assertTrue(ContactReader(ctx.contentResolver, ctx.resources).isValid(phoneUri))+ assertFalse(ContactReader(ctx.contentResolver, ctx.resources).isValid(dead))+ assertFalse(ContactReader(ctx.contentResolver, ctx.resources).isValid(null)) } @Test fun `photo id zero skips photo read`() { FakeContactsProvider.phones[phoneUri.toString()] = FakeContactsProvider.PhoneRow("Alex", "123", photoId = 0)- assertNull(ContactReader(ctx).read(phoneUri)?.photo)+ assertNull(ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri)?.photo) // a photo row with no bytes degrades to null, not a crash FakeContactsProvider.photoBytes = null FakeContactsProvider.phones[phoneUri.toString()] = FakeContactsProvider.PhoneRow("Alex", "123", photoId = 3)- assertNull(ContactReader(ctx).read(phoneUri)?.photo)+ assertNull(ContactReader(ctx.contentResolver, ctx.resources).read(phoneUri)?.photo) } }
emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.ktindex 009b649134..d466f99bf5 100644--- a/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt+++ b/emergency/src/test/java/com/vayunmathur/emergency/platform/RepositoryAndServiceTest.kt@@ -7,7 +7,7 @@ import android.net.Uri import androidx.test.core.app.ApplicationProvider import com.vayunmathur.emergency.data.EmergencyRepository import com.vayunmathur.emergency.notifications.SosNotifications-import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.notifications.SosActionReceiver import com.vayunmathur.emergency.service.SosCountdownService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers
emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.ktindex ac0d5baa93..b74625d11e 100644--- a/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt+++ b/emergency/src/test/java/com/vayunmathur/emergency/ui/EmergencyScreensTest.kt@@ -115,7 +115,7 @@ class EmergencyScreensTest { rule.waitForIdle() val shadow = org.robolectric.Shadows.shadowOf(app) fired = shadow.broadcastIntents.any {- it.action == com.vayunmathur.emergency.receiver.SosActionReceiver.ACTION_MAKE_CALL+ it.action == com.vayunmathur.emergency.notifications.SosActionReceiver.ACTION_MAKE_CALL } || shadow.nextStartedActivity != null if (!fired) Thread.sleep(50) }