Modern Apps git

← Modern-Apps.git

communicate: add multi-SIM line picker for texting/calling and SIM-labeled history

Commit
454da3a359974f7c4c3ee654cbf7e793d20d6731
Author
Vayun Mathur <[email protected]>
When
2026-08-12 18:21 UTC (3 months ago)
Parents
48b7e3b

Diff

communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 94ed06d73c..d18ac1698f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -48,6 +48,7 @@ sealed interface Route : NavKey {         // Serialized as the enum name; defaults keep older back-stack entries valid.         val line: CommunicateLine = CommunicateLine.Sim,         val remoteId: String? = null,+        val subscriptionId: Int? = null,     ) : Route } @@ -115,6 +116,7 @@ private fun CommunicateApp() {                             address = thread.address,                             line = thread.line,                             remoteId = thread.remoteId,+                            subscriptionId = thread.subscriptionId,                         ),                     )                 },@@ -141,6 +143,7 @@ private fun CommunicateApp() {                 address = route.address,                 line = route.line,                 remoteId = route.remoteId,+                subscriptionId = route.subscriptionId,                 onBack = { backStack.pop() },             )         }
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.ktindex 85bfbc909f..5d9cdf802c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateModels.kt@@ -10,6 +10,24 @@ enum class CommunicateLine {     GoogleVoice, } +/**+ * A selectable outgoing line for the line picker: a specific physical SIM (by subscription id)+ * or Google Voice. Mirrors how the OS lets you pick which SIM to call/text from.+ */+sealed interface LineChoice {+    val label: String+    val category: CommunicateLine++    data class Sim(val subscriptionId: Int, override val label: String) : LineChoice {+        override val category get() = CommunicateLine.Sim+    }++    data object GoogleVoice : LineChoice {+        override val label = "Google Voice"+        override val category get() = CommunicateLine.GoogleVoice+    }+}+ data class CommunicateContact(     val id: Long,     val name: String,@@ -35,6 +53,8 @@ data class CommunicateCallLogEntry(     val timestampMillis: Long,     val durationSeconds: Long,     val line: CommunicateLine = CommunicateLine.Sim,+    /** Physical SIM subscription id for SIM calls (from the call log), null if unknown/GV. */+    val subscriptionId: Int? = null, )  /**@@ -61,6 +81,7 @@ data class SmsThread(      * [threadId] (hash of [remoteId]) so list keys and navigation still work.      */     val remoteId: String? = null,+    val subscriptionId: Int? = null, )  data class SmsMessage(@@ -74,4 +95,5 @@ data class SmsMessage(     val line: CommunicateLine = CommunicateLine.Sim,     val remoteId: String? = null,     val attachments: List<CommunicateAttachment> = emptyList(),+    val subscriptionId: Int? = null, )
communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.ktindex 90c5450d6f..a327368287 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/CommunicateRepository.kt@@ -82,6 +82,7 @@ object CommunicateRepository {             CallLog.Calls.TYPE,             CallLog.Calls.DATE,             CallLog.Calls.DURATION,+            CallLog.Calls.PHONE_ACCOUNT_ID,         )         return runCatching {             context.contentResolver.query(@@ -98,9 +99,17 @@ object CommunicateRepository {                     val type = cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE)                     val date = cursor.getColumnIndexOrThrow(CallLog.Calls.DATE)                     val duration = cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION)+                    val account = cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID)+                    val activeSubs = SimManager.activeSims(context).map { it.subscriptionId }.toSet()                      while (cursor.moveToNext()) {                         val phoneNumber = cursor.getString(number).orEmpty().ifBlank { "Unknown" }+                        // PHONE_ACCOUNT_ID is the SIM's subscription id on most devices; keep it+                        // only when it maps to an active SIM so we can label the row by SIM.+                        val subId = account.takeIf { it >= 0 }+                            ?.let { cursor.getString(it) }+                            ?.toIntOrNull()+                            ?.takeIf { it in activeSubs }                         add(                             CommunicateCallLogEntry(                                 id = cursor.getLong(id),@@ -109,6 +118,7 @@ object CommunicateRepository {                                 type = cursor.getInt(type).toCommunicateCallType(),                                 timestampMillis = cursor.getLong(date),                                 durationSeconds = cursor.getLong(duration),+                                subscriptionId = subId,                             )                         )                     }@@ -132,6 +142,7 @@ object CommunicateRepository {                     snippet = newest.body,                     timestampMillis = newest.timestampMillis,                     unreadCount = messages.count { !it.outgoing && !it.read },+                    subscriptionId = newest.subscriptionId,                 )             }             .sortedByDescending { it.timestampMillis }@@ -148,6 +159,7 @@ object CommunicateRepository {             Telephony.Sms.DATE,             Telephony.Sms.TYPE,             Telephony.Sms.READ,+            Telephony.Sms.SUBSCRIPTION_ID,         )         val selection = threadId?.let { "${Telephony.Sms.THREAD_ID} = ?" }         val args = threadId?.let { arrayOf(it.toString()) }@@ -167,6 +179,7 @@ object CommunicateRepository {                     val date = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE)                     val type = cursor.getColumnIndexOrThrow(Telephony.Sms.TYPE)                     val read = cursor.getColumnIndexOrThrow(Telephony.Sms.READ)+                    val sub = cursor.getColumnIndex(Telephony.Sms.SUBSCRIPTION_ID)                      while (cursor.moveToNext()) {                         add(@@ -179,6 +192,7 @@ object CommunicateRepository {                                 outgoing = cursor.getInt(type) == Telephony.Sms.MESSAGE_TYPE_SENT ||                                     cursor.getInt(type) == Telephony.Sms.MESSAGE_TYPE_OUTBOX,                                 read = cursor.getInt(read) != 0,+                                subscriptionId = sub.takeIf { it >= 0 }?.let { cursor.getInt(it) }?.takeIf { it >= 0 },                             )                         )                     }@@ -207,15 +221,27 @@ object CommunicateRepository {     }      fun placeCall(context: Context, number: String) {+        placeCall(context, choice = null, number = number)+    }++    /**+     * Place a call from a chosen line. Google Voice routes through the self-managed account; a SIM+     * choice places via that SIM's [PhoneAccountHandle]; null uses the default outgoing account.+     */+    fun placeCall(context: Context, choice: LineChoice?, number: String) {         if (number.isBlank()) return+        if (choice is LineChoice.GoogleVoice) {+            com.vayunmathur.communicate.telephony.GoogleVoiceTelecom.placeOutgoing(context, number)+            return+        }         val uri = Uri.fromParts("tel", number, null)         if (context.hasPermission(Manifest.permission.CALL_PHONE)) {             try {                 val telecomManager = context.getSystemService(TelecomManager::class.java)                 val extras = Bundle()-                telecomManager.getDefaultOutgoingPhoneAccount(PhoneAccount.SCHEME_TEL)?.let {-                    extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, it)-                }+                val handle = (choice as? LineChoice.Sim)?.let { phoneAccountHandleForSub(context, it.subscriptionId) }+                    ?: telecomManager.getDefaultOutgoingPhoneAccount(PhoneAccount.SCHEME_TEL)+                handle?.let { extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, it) }                 telecomManager.placeCall(uri, extras)                 return             } catch (_: Exception) {@@ -225,6 +251,16 @@ object CommunicateRepository {         ExternalIntents.launch(context, Intent(Intent.ACTION_DIAL, uri))     } +    /** Map a SIM subscription id to its Telecom [PhoneAccountHandle] (handle id is the sub id). */+    private fun phoneAccountHandleForSub(context: Context, subscriptionId: Int): android.telecom.PhoneAccountHandle? {+        if (subscriptionId < 0) return null+        if (!context.hasPermission(Manifest.permission.READ_PHONE_STATE)) return null+        val tm = context.getSystemService(TelecomManager::class.java) ?: return null+        return runCatching {+            tm.callCapablePhoneAccounts.firstOrNull { it.id == subscriptionId.toString() }+        }.getOrNull()+    }+     fun openSmsComposer(context: Context, number: String? = null, body: String? = null) {         val uri = if (number.isNullOrBlank()) "smsto:".toUri() else "smsto:$number".toUri()         val intent = Intent(Intent.ACTION_SENDTO, uri).apply {@@ -233,6 +269,11 @@ object CommunicateRepository {         ExternalIntents.launch(context, intent)     } +    /** Resolve (or create) the SIM thread id for an address, so a new SIM conversation shows history. */+    fun getOrCreateSmsThreadId(context: Context, address: String): Long? = runCatching {+        Telephony.Threads.getOrCreateThreadId(context, address)+    }.getOrNull()+     // ------------------------------------------------------------------     // Google Voice merge (second line)     //@@ -270,21 +311,19 @@ object CommunicateRepository {     }      /**-     * Dispatch an outgoing message to the right line. SIM uses the existing composer path;-     * Google Voice posts through `api2thread/sendsms`. Returns true on success.+     * Dispatch an outgoing message from a chosen line. A SIM choice sends via that SIM's+     * [android.telephony.SmsManager] and records it in the provider; Google Voice mints a token in+     * an offscreen WebView and posts `api2thread/sendsms`. Returns true on success.      */     suspend fun sendMessage(         context: Context,-        line: CommunicateLine,+        choice: LineChoice,         address: String,         body: String,         threadRemoteId: String? = null,-    ): Boolean = when (line) {-        CommunicateLine.Sim -> {-            openSmsComposer(context, address, body)-            true-        }-        CommunicateLine.GoogleVoice -> runCatching {+    ): Boolean = when (choice) {+        is LineChoice.Sim -> sendSimSms(context, choice.subscriptionId, address, body)+        LineChoice.GoogleVoice -> runCatching {             // The bot-defense token is minted invisibly in an offscreen WebView; the app then             // builds and sends the sendsms API call itself using that token.             val activity = context as? android.app.Activity ?: return@runCatching false@@ -296,6 +335,38 @@ object CommunicateRepository {         }.getOrDefault(false)     } +    /** Send an SMS from a specific SIM subscription and store it in the Sent box. */+    private fun sendSimSms(context: Context, subscriptionId: Int, address: String, body: String): Boolean {+        if (address.isBlank() || body.isBlank()) return false+        if (!context.hasPermission(Manifest.permission.SEND_SMS)) {+            openSmsComposer(context, address, body)+            return true+        }+        return runCatching {+            val base = context.getSystemService(android.telephony.SmsManager::class.java)+            val sms = if (subscriptionId >= 0) base.createForSubscriptionId(subscriptionId) else base+            val parts = sms.divideMessage(body)+            if (parts.size > 1) {+                sms.sendMultipartTextMessage(address, null, parts, null, null)+            } else {+                sms.sendTextMessage(address, null, body, null, null)+            }+            // Record in the provider Sent box so it shows in the thread (we're the default SMS app).+            runCatching {+                val values = android.content.ContentValues().apply {+                    put(Telephony.Sms.ADDRESS, address)+                    put(Telephony.Sms.BODY, body)+                    put(Telephony.Sms.DATE, System.currentTimeMillis())+                    put(Telephony.Sms.READ, 1)+                    put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_SENT)+                    if (subscriptionId >= 0) put(Telephony.Sms.SUBSCRIPTION_ID, subscriptionId)+                }+                context.contentResolver.insert(Telephony.Sms.Sent.CONTENT_URI, values)+            }+            true+        }.getOrDefault(false)+    }+     /** Toggle a Google Voice thread attribute (read/archive/spam) via batchupdateattributes. */     suspend fun updateGoogleVoiceThread(         context: Context,
communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.ktnew file mode 100644index 0000000000..4fa08e11d1--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/SimManager.kt@@ -0,0 +1,68 @@+package com.vayunmathur.communicate.data++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.telephony.SubscriptionManager+import androidx.core.content.ContextCompat++/** A physical SIM subscription available for texting/calling. */+data class CommunicateSim(+    val subscriptionId: Int,+    val slotIndex: Int,+    val displayName: String,+)++/**+ * Enumerates the device's active SIM subscriptions so the app can offer per-SIM texting/calling+ * (like the system dialer/messages) and label call/message history by SIM.+ *+ * Reads require READ_PHONE_STATE; when it isn't granted we fall back to a single default SIM+ * choice so the app still works on the primary line.+ */+object SimManager {++    fun activeSims(context: Context): List<CommunicateSim> {+        if (!context.hasPhoneStatePermission()) return emptyList()+        val sm = context.getSystemService(SubscriptionManager::class.java) ?: return emptyList()+        return runCatching {+            sm.activeSubscriptionInfoList?.map { info ->+                CommunicateSim(+                    subscriptionId = info.subscriptionId,+                    slotIndex = info.simSlotIndex,+                    displayName = info.displayName?.toString()?.takeIf { it.isNotBlank() }+                        ?: info.carrierName?.toString()?.takeIf { it.isNotBlank() }+                        ?: "SIM ${info.simSlotIndex + 1}",+                )+            }.orEmpty()+        }.getOrDefault(emptyList())+    }++    /** Selectable SIM lines. Falls back to a single default SIM when none can be enumerated. */+    fun simLineChoices(context: Context): List<LineChoice.Sim> {+        val sims = activeSims(context)+        if (sims.isNotEmpty()) {+            val multi = sims.size > 1+            return sims.map { sim ->+                // With multiple SIMs, disambiguate by slot; with one, just show its name.+                val label = if (multi) "${sim.displayName}" else sim.displayName+                LineChoice.Sim(sim.subscriptionId, label)+            }+        }+        val defaultSub = defaultSmsSubscriptionId()+        return listOf(LineChoice.Sim(defaultSub, "SIM"))+    }++    fun labelForSubscription(context: Context, subscriptionId: Int?): String? {+        if (subscriptionId == null) return null+        return activeSims(context).firstOrNull { it.subscriptionId == subscriptionId }?.displayName+    }++    fun defaultSmsSubscriptionId(): Int = runCatching {+        SubscriptionManager.getDefaultSmsSubscriptionId()+    }.getOrDefault(SubscriptionManager.INVALID_SUBSCRIPTION_ID)++    private fun Context.hasPhoneStatePermission(): Boolean =+        ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) ==+            PackageManager.PERMISSION_GRANTED+}
communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.ktindex eca7124cae..e96a23a598 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CallLogsScreen.kt@@ -87,7 +87,7 @@ private fun CallLogRow(entry: CommunicateCallLogEntry, onClick: () -> Unit) {                     overflow = TextOverflow.Ellipsis,                     fontWeight = if (entry.type == CommunicateCallType.Missed) FontWeight.Bold else FontWeight.Medium,                 )-                LineBadge(entry.line, modifier = Modifier.padding(start = 6.dp))+                LineBadge(entry.line, entry.subscriptionId, modifier = Modifier.padding(start = 6.dp))             }         },         supportingContent = {
communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.ktindex c54dcd49dc..f1ea1ee6f1 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateUi.kt@@ -8,14 +8,19 @@ import android.text.format.DateFormat import android.text.format.DateUtils import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource@@ -25,8 +30,14 @@ import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import com.vayunmathur.communicate.R import com.vayunmathur.communicate.data.CommunicateLine+import com.vayunmathur.communicate.data.LineChoice+import com.vayunmathur.communicate.data.SimManager+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.IconArrowDropDown import com.vayunmathur.library.ui.IconCall import com.vayunmathur.library.ui.IconSms import com.vayunmathur.library.ui.MaterialTheme@@ -160,13 +171,12 @@ fun initialsFor(text: String): String = text     .ifBlank { "?" }  /**- * Small pill that tags a row with the line (SIM vs Google Voice) it belongs to, so the- * merged inbox / call log stays legible. Only Google Voice is badged; SIM is the implicit- * default and left unbadged to avoid noise.+ * Small pill tagging a row with a line label (a SIM's name or "Voice"), so the merged inbox /+ * call log stays legible across multiple SIMs + Google Voice. Renders nothing when [text] is null.  */ @Composable-fun LineBadge(line: CommunicateLine, modifier: Modifier = Modifier) {-    if (line != CommunicateLine.GoogleVoice) return+fun LineTag(text: String?, modifier: Modifier = Modifier) {+    if (text.isNullOrBlank()) return     Surface(         shape = RoundedCornerShape(50),         color = MaterialTheme.colorScheme.tertiaryContainer,@@ -174,10 +184,77 @@ fun LineBadge(line: CommunicateLine, modifier: Modifier = Modifier) {         modifier = modifier,     ) {         Text(-            stringResource(R.string.line_gv),+            text,             modifier = Modifier.padding(horizontal = 6.dp, vertical = 1.dp),             fontSize = 10.sp,             fontWeight = FontWeight.Bold,+            maxLines = 1,         )     } }++/** The user-facing label for a stored line, given its category + SIM subscription (if any). */+@Composable+fun lineLabel(line: CommunicateLine, subscriptionId: Int?, alwaysShowSim: Boolean = false): String? {+    val context = LocalContext.current+    return when (line) {+        CommunicateLine.GoogleVoice -> stringResource(R.string.line_gv)+        CommunicateLine.Sim -> {+            val sims = remember { SimManager.activeSims(context) }+            // Only label SIM rows when there's more than one SIM (or explicitly requested).+            if (!alwaysShowSim && sims.size <= 1) return null+            sims.firstOrNull { it.subscriptionId == subscriptionId }?.displayName+        }+    }+}++/** Convenience: tag for a stored line (SIM name / "Voice"). */+@Composable+fun LineBadge(line: CommunicateLine, subscriptionId: Int? = null, modifier: Modifier = Modifier) {+    LineTag(lineLabel(line, subscriptionId), modifier = modifier)+}++/** All selectable outgoing lines: each active SIM plus Google Voice when signed in. */+@Composable+fun rememberLineChoices(): List<LineChoice> {+    val context = LocalContext.current+    val session = remember { GoogleVoiceSession.get(context) }+    val gv by session.signedInFlow.collectAsState(initial = false)+    return remember(gv) {+        SimManager.simLineChoices(context) + if (gv) listOf(LineChoice.GoogleVoice) else emptyList()+    }+}++/** Dropdown that lets the user pick which line (SIM or Google Voice) to send/call from. */+@Composable+fun LineSelector(+    choices: List<LineChoice>,+    selected: LineChoice,+    onSelect: (LineChoice) -> Unit,+    modifier: Modifier = Modifier,+) {+    var expanded by remember { mutableStateOf(false) }+    Box(modifier) {+        Surface(+            onClick = { expanded = true },+            shape = RoundedCornerShape(50),+            color = MaterialTheme.colorScheme.surfaceVariant,+        ) {+            Row(+                verticalAlignment = Alignment.CenterVertically,+                modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),+            ) {+                Text(selected.label, style = MaterialTheme.typography.labelLarge, maxLines = 1)+                IconArrowDropDown()+            }+        }+        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+            choices.forEach { choice ->+                DropdownMenuItem(+                    text = { Text(choice.label) },+                    onClick = { onSelect(choice); expanded = false },+                )+            }+        }+    }+}
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex e275487f09..dd30abea84 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -64,13 +64,26 @@ fun ConversationScreen(     address: String,     line: CommunicateLine,     remoteId: String?,+    subscriptionId: Int? = null,     onBack: () -> Unit, ) {     val context = LocalContext.current     val scope = rememberCoroutineScope()     var draft by remember(threadId) { mutableStateOf("") }-    // Bumped after a Google Voice send to re-fetch the thread (no realtime channel yet).+    // Bumped after a send to re-fetch the thread.     var refresh by remember(threadId) { mutableIntStateOf(0) }+    val lineChoices = rememberLineChoices()+    // Default the send line to this thread's line (matching SIM subscription when known).+    var selectedLine by remember(threadId, lineChoices) {+        mutableStateOf(+            when (line) {+                CommunicateLine.GoogleVoice ->+                    lineChoices.firstOrNull { it is com.vayunmathur.communicate.data.LineChoice.GoogleVoice }+                CommunicateLine.Sim ->+                    lineChoices.firstOrNull { it is com.vayunmathur.communicate.data.LineChoice.Sim && it.subscriptionId == subscriptionId }+            } ?: lineChoices.firstOrNull(),+        )+    }     val thread = remember(threadId) {         SmsThread(             threadId = threadId,@@ -153,23 +166,26 @@ fun ConversationScreen(             ComposeSmsRow(                 draft = draft,                 onDraftChange = { draft = it },+                lineSelector = {+                    val sel = selectedLine+                    if (lineChoices.size > 1 && sel != null) {+                        LineSelector(choices = lineChoices, selected = sel, onSelect = { selectedLine = it })+                    }+                },                 onSend = {                     val text = draft.trim()-                    if (text.isEmpty()) return@ComposeSmsRow-                    when (line) {-                        CommunicateLine.Sim -> {-                            CommunicateRepository.openSmsComposer(context, address, text)-                            draft = ""-                        }-                        CommunicateLine.GoogleVoice -> {-                            draft = ""-                            scope.launch {-                                val ok = CommunicateRepository.sendMessage(-                                    context, line, address, text, remoteId,-                                )-                                if (ok) refresh++ else AppMessages.show(context.getString(R.string.gv_send_failed))-                            }-                        }+                    val choice = selectedLine+                    if (text.isEmpty() || choice == null) return@ComposeSmsRow+                    draft = ""+                    scope.launch {+                        val ok = CommunicateRepository.sendMessage(+                            context,+                            choice,+                            address,+                            text,+                            if (choice is com.vayunmathur.communicate.data.LineChoice.GoogleVoice) remoteId else null,+                        )+                        if (ok) refresh++ else AppMessages.show(context.getString(R.string.gv_send_failed))                     }                 },             )@@ -232,6 +248,7 @@ private fun MessagesContent(padding: PaddingValues, rows: List<SmsMessage>?) { private fun ComposeSmsRow(     draft: String,     onDraftChange: (String) -> Unit,+    lineSelector: @Composable () -> Unit,     onSend: () -> Unit, ) {     Surface(@@ -246,12 +263,13 @@ private fun ComposeSmsRow(                 .padding(horizontal = 8.dp, vertical = 8.dp),             verticalAlignment = Alignment.CenterVertically,         ) {+            lineSelector()             OutlinedTextField(                 value = draft,                 onValueChange = onDraftChange,                 modifier = Modifier                     .weight(1f)-                    .padding(end = 4.dp),+                    .padding(horizontal = 4.dp),                 placeholder = { Text(stringResource(R.string.message_hint)) },                 maxLines = 5,                 shape = RoundedCornerShape(24.dp),
communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.ktindex 04f89eb41c..2bd69c674f 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/DialerScreen.kt@@ -69,22 +69,35 @@ fun DialerScreen() {     val clipboard = LocalClipboard.current     val scope = rememberCoroutineScope()     var number by remember { mutableStateOf("") }-    val session = remember { GoogleVoiceSession.get(context) }-    val gvSignedIn by session.signedInFlow.collectAsState(initial = false)-    var useGoogleVoice by remember { mutableStateOf(false) }+    val lineChoices = rememberLineChoices()+    var selectedLine by remember(lineChoices) { mutableStateOf(lineChoices.firstOrNull()) }      fun place(target: String) {         if (target.isBlank()) return-        if (useGoogleVoice && gvSignedIn) {+        val choice = selectedLine+        if (choice is com.vayunmathur.communicate.data.LineChoice.GoogleVoice) {             GoogleVoiceCallManager.init(context)-            GoogleVoiceTelecom.placeOutgoing(context, target)-        } else {-            CommunicateRepository.placeCall(context, target)         }+        CommunicateRepository.placeCall(context, choice, target)     }      Scaffold(-        topBar = { TopAppBar(title = { Text(stringResource(R.string.dialer_title)) }) },+        topBar = {+            TopAppBar(+                title = { Text(stringResource(R.string.dialer_title)) },+                actions = {+                    val sel = selectedLine+                    if (lineChoices.size > 1 && sel != null) {+                        LineSelector(+                            choices = lineChoices,+                            selected = sel,+                            onSelect = { selectedLine = it },+                            modifier = Modifier.padding(end = 8.dp),+                        )+                    }+                },+            )+        },     ) { padding ->         DefaultDialerGate(modifier = Modifier.padding(padding)) { roleRevision ->             Column(@@ -92,21 +105,6 @@ fun DialerScreen() {                     .padding(padding)                     .fillMaxSize(),             ) {-                if (gvSignedIn) {-                    Row(-                        modifier = Modifier-                            .fillMaxWidth()-                            .padding(horizontal = 20.dp, vertical = 8.dp),-                        verticalAlignment = Alignment.CenterVertically,-                    ) {-                        Text(-                            stringResource(R.string.account_google_voice),-                            modifier = Modifier.weight(1f),-                            style = MaterialTheme.typography.bodyMedium,-                        )-                        Switch(checked = useGoogleVoice, onCheckedChange = { useGoogleVoice = it })-                    }-                }                 PermissionGate(                     permission = Manifest.permission.READ_CONTACTS,                     message = stringResource(R.string.permission_contacts_message),
communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.ktindex 04b81b7172..4d4ac62d31 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt@@ -62,29 +62,33 @@ import kotlinx.coroutines.withContext @Composable fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit) {     val context = LocalContext.current-    val session = remember { GoogleVoiceSession.get(context) }-    val gvSignedIn by session.signedInFlow.collectAsState(initial = false)+    val lineChoices = rememberLineChoices()     var showPicker by remember { mutableStateOf(false) }      if (showPicker) {         NewMessagePicker(+            choices = lineChoices,             onDismiss = { showPicker = false },-            onSim = {-                showPicker = false-                CommunicateRepository.openSmsComposer(context)-            },-            onGoogleVoice = { number ->+            onCompose = { choice, number ->                 showPicker = false+                val sim = choice as? com.vayunmathur.communicate.data.LineChoice.Sim+                val threadId = if (sim != null) {+                    CommunicateRepository.getOrCreateSmsThreadId(context, number)+                        ?: CommunicateRepository.stableThreadId(number)+                } else {+                    CommunicateRepository.stableThreadId(number)+                }                 onOpenThread(                     SmsThread(-                        threadId = CommunicateRepository.stableThreadId(number),+                        threadId = threadId,                         address = number,                         displayName = null,                         snippet = "",                         timestampMillis = System.currentTimeMillis(),                         unreadCount = 0,-                        line = CommunicateLine.GoogleVoice,+                        line = choice.category,                         remoteId = null,+                        subscriptionId = sim?.subscriptionId,                     ),                 )             },@@ -102,7 +106,8 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit         },         floatingActionButton = {             FloatingActionButton(onClick = {-                if (gvSignedIn) showPicker = true else CommunicateRepository.openSmsComposer(context)+                // With more than one line, let the user pick which SIM / Google Voice to text from.+                if (lineChoices.size > 1) showPicker = true else CommunicateRepository.openSmsComposer(context)             }) {                 IconAdd()             }@@ -166,7 +171,7 @@ private fun MessageThreadRow(thread: SmsThread, onClick: () -> Unit) {                     overflow = TextOverflow.Ellipsis,                     modifier = Modifier.weight(1f, fill = false),                 )-                LineBadge(thread.line, modifier = Modifier.padding(start = 6.dp))+                LineBadge(thread.line, thread.subscriptionId, modifier = Modifier.padding(start = 6.dp))                 Spacer(Modifier.weight(1f))                 Spacer(Modifier.width(8.dp))                 Text(@@ -227,33 +232,22 @@ private fun UnreadBadge(count: Int) { }  /**- * FAB flow when a Google Voice line is connected: pick which line to compose from. SIM opens- * the system composer (we're the default SMS app); Google Voice collects a recipient number- * and opens a new GV conversation.+ * FAB flow when more than one line is available: enter a recipient number and pick which line+ * (SIM or Google Voice) to compose from, then open that conversation.  */ @Composable private fun NewMessagePicker(+    choices: List<com.vayunmathur.communicate.data.LineChoice>,     onDismiss: () -> Unit,-    onSim: () -> Unit,-    onGoogleVoice: (String) -> Unit,+    onCompose: (com.vayunmathur.communicate.data.LineChoice, String) -> Unit, ) {     var number by remember { mutableStateOf("") }+    var selected by remember(choices) { mutableStateOf(choices.firstOrNull()) }     AlertDialog(         onDismissRequest = onDismiss,-        title = { Text(stringResource(R.string.choose_line)) },+        title = { Text(stringResource(R.string.new_message)) },         text = {             Column {-                ListItem(-                    leadingContent = { IconSms() },-                    content = { Text(stringResource(R.string.account_sim)) },-                    colors = ListItemDefaults.colors(containerColor = Color.Transparent),-                    modifier = Modifier.clickable(onClick = onSim),-                )-                HorizontalDivider()-                ListItem(-                    content = { Text(stringResource(R.string.account_google_voice)) },-                    colors = ListItemDefaults.colors(containerColor = Color.Transparent),-                )                 OutlinedTextField(                     value = number,                     onValueChange = { number = it.filter { c -> c.isDigit() || c == '+' } },@@ -261,13 +255,25 @@ private fun NewMessagePicker(                     placeholder = { Text(stringResource(R.string.phone_number)) },                     singleLine = true,                 )+                Spacer(Modifier.size(12.dp))+                Row(verticalAlignment = Alignment.CenterVertically) {+                    Text(+                        stringResource(R.string.choose_line),+                        style = MaterialTheme.typography.labelLarge,+                        modifier = Modifier.padding(end = 8.dp),+                    )+                    val sel = selected+                    if (sel != null) {+                        LineSelector(choices = choices, selected = sel, onSelect = { selected = it })+                    }+                }             }         },         confirmButton = {             TextButton(-                onClick = { if (number.isNotBlank()) onGoogleVoice(number) },-                enabled = number.isNotBlank(),-            ) { Text(stringResource(R.string.account_google_voice)) }+                onClick = { val s = selected; if (s != null && number.isNotBlank()) onCompose(s, number) },+                enabled = selected != null && number.isNotBlank(),+            ) { Text(stringResource(R.string.send)) }         },         dismissButton = {             TextButton(onClick = onDismiss) { Text(stringResource(R.string.clear)) }