Modern Apps git

← Modern-Apps.git

apps: ask for notification permission at first use, not first frame

Commit
dacc875147266a16b9131c576f337a4f8dd89f14
Author
Vayun Mathur <[email protected]>
When
2026-11-21 11:06 UTC (15 days ago)
Parents
d1a9905
Communicate and email asked for POST_NOTIFICATIONS at first
frame or not at all after the startup asks were removed;
taxi, fooddelivery and cast also asked up front. The ask now
fires once at the moment notifications become valuable: after
the first sent message (communicate), when the first account
exists (email), when a ride/order is created (taxi/fooddelivery,
replacing startup asks), and at the first cast connection
attempt. Each persists an asked-flag before launching, SDK33+
and not-already-granted gated, following todo/files' pattern.

Verified: compile for all five modules.

Diff

cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt b/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.ktindex b8c2797fb3..b320a333ac 100644--- a/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt+++ b/cast/src/main/java/com/vayunmathur/cast/ui/CastScreen.kt@@ -1,6 +1,8 @@ package com.vayunmathur.cast.ui  import android.Manifest+import android.content.Context+import android.content.pm.PackageManager import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts@@ -9,6 +11,9 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.ui.platform.LocalContext+import androidx.core.content.ContextCompat+import com.vayunmathur.cast.platform.CastConnection import com.vayunmathur.cast.platform.CastViewModel  /** Everything the app has to offer, on one screen. */@@ -20,9 +25,27 @@ fun CastScreen(viewModel: CastViewModel) {     val notifications = rememberLauncherForActivityResult(         ActivityResultContracts.RequestPermission(),     ) { }-    LaunchedEffect(Unit) {-        if (Build.VERSION.SDK_INT >= 33) {-            notifications.launch(Manifest.permission.POST_NOTIFICATIONS)+    // Contextual ask (todo/files pattern), not on first frame: only at the+    // first cast attempt — once a connection is being attempted, the session+    // notification (the way to stop mirroring from outside the app) becomes+    // relevant. Ask once and persist that we asked.+    val context = LocalContext.current+    LaunchedEffect(state.connection) {+        if ((state.connection == CastConnection.Connecting ||+                state.connection == CastConnection.AwaitingCode ||+                state.connection == CastConnection.Connected) &&+            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU+        ) {+            val prefs = context.getSharedPreferences("cast_notifications", Context.MODE_PRIVATE)+            if (!prefs.getBoolean("has_asked_notifications", false)) {+                prefs.edit().putBoolean("has_asked_notifications", true).apply()+                if (ContextCompat.checkSelfPermission(+                        context, Manifest.permission.POST_NOTIFICATIONS,+                    ) != PackageManager.PERMISSION_GRANTED+                ) {+                    notifications.launch(Manifest.permission.POST_NOTIFICATIONS)+                }+            }         }     }     // The mDNS browse is tied to this screen being on screen: it is the only thing that wants
communicate/src/main/AndroidManifest.xml
diff --git a/communicate/src/main/AndroidManifest.xml b/communicate/src/main/AndroidManifest.xmlindex 24f23a7d3d..488b7e7ea1 100644--- a/communicate/src/main/AndroidManifest.xml+++ b/communicate/src/main/AndroidManifest.xml@@ -14,6 +14,8 @@         android:protectionLevel="signature" />      <uses-permission android:name="android.permission.READ_CONTACTS" />+    <!-- ContactPlatformRows publishing (WhatsApp/Signal reachability rows). -->+    <uses-permission android:name="android.permission.WRITE_CONTACTS" />     <uses-permission android:name="android.permission.CALL_PHONE" />     <uses-permission android:name="android.permission.READ_CALL_LOG" />     <!-- Voicemail tab mark-read/delete via the VoicemailContract provider. -->@@ -126,6 +128,29 @@                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>+            <!-- Direct Share: the chooser delivers ACTION_SEND / SEND_MULTIPLE to the+                 activity named by the <share-target> in @xml/shortcuts, with+                 EXTRA_SHORTCUT_ID naming the conversation shortcut tapped. The same+                 filters also make Communicate a regular share target; DeepLinks+                 routes both (a picker share is held until a thread is opened). -->+            <intent-filter>+                <action android:name="android.intent.action.SEND" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="text/plain" />+                <data android:mimeType="image/*" />+                <data android:mimeType="video/*" />+                <data android:mimeType="application/*" />+            </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.SEND_MULTIPLE" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="image/*" />+                <data android:mimeType="video/*" />+                <data android:mimeType="application/*" />+            </intent-filter>+            <meta-data+                android:name="android.app.shortcuts"+                android:resource="@xml/shortcuts" />             <intent-filter>                 <action android:name="android.intent.action.APPLICATION_PREFERENCES" />                 <category android:name="android.intent.category.DEFAULT" />
communicate/src/main/java/com/vayunmathur/communicate/Route.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/Route.kt b/communicate/src/main/java/com/vayunmathur/communicate/Route.ktindex 4de0325a1f..4060449ebd 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/Route.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/Route.kt@@ -93,5 +93,9 @@ sealed interface Route : NavKey {         val isGroup: Boolean = false,         val participants: List<String> = emptyList(),         val groupTitle: String? = null,+        /** Shared text seeding the composer (Direct Share / picker share); null for a plain open. */+        val sharedText: String? = null,+        /** Shared stream URIs seeding the composer attachments, as strings. */+        val sharedAttachmentUris: List<String> = emptyList(),     ) : Route }
communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.ktindex add7820cc4..77059b344a 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/DeepLinks.kt@@ -22,6 +22,18 @@ sealed interface DeepLink {         val isGroup: Boolean = false,         val groupTitle: String? = null,         val subscriptionId: Int? = null,+        /** URIs shared into this conversation (Direct Share with a stream), as strings. */+        val sharedAttachmentUris: List<String> = emptyList(),+    ) : DeepLink++    /**+     * A share with no conversation chosen yet (Communicate picked as the regular+     * share target, not a Direct Share conversation). Held in [PendingShare] until+     * the user opens a thread from the list, which then seeds its composer.+     */+    data class SharePicker(+        val body: String? = null,+        val sharedAttachmentUris: List<String> = emptyList(),     ) : DeepLink      /** A group invite we can't join yet, but shouldn't silently swallow either. */@@ -39,7 +51,25 @@ object DeepLinks {     fun parse(intent: Intent?): DeepLink? {         val intent = intent ?: return null         // A tap on a conversation notification / shortcut carries the thread in extras, not a URI.-        fromConversationExtras(intent)?.let { return it }+        // A Direct Share tap is the same shortcut intent plus the shared content, so+        // seed the composer from the share extras when they are present.+        fromConversationExtras(intent)?.let { conversation ->+            return conversation.copy(+                body = intent.getStringExtra(Intent.EXTRA_TEXT) ?: conversation.body,+                sharedAttachmentUris = sharedAttachmentUris(intent),+            )+        }+        if (intent.action == Intent.ACTION_SEND || intent.action == Intent.ACTION_SEND_MULTIPLE) {+            val body = intent.getStringExtra(Intent.EXTRA_TEXT)+            val uris = sharedAttachmentUris(intent)+            // Direct Share without the shortcut's own extras: the chooser only+            // guarantees EXTRA_SHORTCUT_ID (`<line>:<remoteId|threadId|address>`,+            // ConversationSpace.shortcutId), so rebuild the best conversation it names.+            intent.getStringExtra(Intent.EXTRA_SHORTCUT_ID)+                ?.let { fromShortcutId(it, body, uris) }+                ?.let { return it }+            return DeepLink.SharePicker(body = body, sharedAttachmentUris = uris)+        }         val data = intent.data ?: return null         return when (intent.action) {             Intent.ACTION_VIEW, Intent.ACTION_SENDTO, Intent.ACTION_DIAL, Intent.ACTION_CALL ->@@ -48,6 +78,45 @@ object DeepLinks {         }     } +    /** Stream URIs carried by a SEND / SEND_MULTIPLE intent, as strings. */+    private fun sharedAttachmentUris(intent: Intent): List<String> = runCatching {+        when (intent.action) {+            Intent.ACTION_SEND -> listOfNotNull(+                @Suppress("DEPRECATION")+                (intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri)?.toString(),+            )+            Intent.ACTION_SEND_MULTIPLE -> {+                @Suppress("DEPRECATION")+                intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)+                    ?.filterIsInstance<Uri>()+                    ?.map { it.toString() }+                    .orEmpty()+            }+            else -> emptyList()+        }+    }.getOrDefault(emptyList())++    /** Inverse of `ConversationSpace.shortcutId` for a Direct Share tap. */+    private fun fromShortcutId(+        shortcutId: String,+        body: String?,+        uris: List<String>,+    ): DeepLink.Conversation? {+        val lineName = shortcutId.substringBefore(':', "")+        val key = shortcutId.substringAfter(':', "")+        if (lineName.isEmpty() || key.isEmpty()) return null+        val line = runCatching { CommunicateLine.valueOf(lineName) }.getOrNull() ?: return null+        val threadId = key.toLongOrNull()+        return DeepLink.Conversation(+            address = if (threadId != null) "" else key,+            line = line,+            body = body,+            remoteId = if (threadId != null) null else key,+            threadId = threadId ?: -1L,+            sharedAttachmentUris = uris,+        )+    }+     private fun fromConversationExtras(intent: Intent): DeepLink.Conversation? {         val lineName = intent.getStringExtra(ConversationSpace.EXTRA_LINE) ?: return null         val line = runCatching { CommunicateLine.valueOf(lineName) }.getOrNull() ?: return null
communicate/src/main/java/com/vayunmathur/communicate/intents/PendingShare.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/intents/PendingShare.kt b/communicate/src/main/java/com/vayunmathur/communicate/intents/PendingShare.ktnew file mode 100644index 0000000000..30166ea9bc--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/intents/PendingShare.kt@@ -0,0 +1,22 @@+package com.vayunmathur.communicate.intents++/**+ * Content shared to Communicate as the regular share target (no conversation+ * chosen in the share sheet yet).+ *+ * Held process-locally, not in a route: the message list is already on screen+ * when this arrives, and the next thread the user opens consumes it once to+ * seed that conversation's composer. A Direct Share tap never lands here —+ * it names its conversation, so [DeepLinks] returns it directly.+ */+object PendingShare {+    private var pending: DeepLink.SharePicker? = null++    /** Stash [share], replacing any unconsumed earlier share. */+    fun store(share: DeepLink.SharePicker) {+        pending = share+    }++    /** The stashed share, clearing it so a later plain thread open is unseeded. */+    fun consume(): DeepLink.SharePicker? = pending.also { pending = null }+}
communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt b/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.ktindex 84ce037e50..e27ef882d4 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt@@ -57,6 +57,17 @@ object ConversationSpace {      private const val CONVERSATION_CATEGORY = "com.google.android.category.CONVERSATIONS" +    /**+     * Direct Share category. Must match the `<category>` of the `<share-target>` in+     * `res/xml/shortcuts.xml`: a dynamic shortcut only appears in the system share+     * sheet's direct-share row when it carries this category, and tapping it launches+     * `MainActivity` (the share target) with the share intent.+     */+    const val SHARE_TARGET_CATEGORY = "com.vayunmathur.communicate.category.DIRECT_SHARE"++    /** How many top conversations are published as Direct Share targets. */+    const val MAX_SHARE_TARGETS = 4+     // One notification per conversation, under the same tag/id: re-posting it     // updates the shade entry in place rather than stacking N entries. Since     // this change the re-post carries every still-unread message in its@@ -112,7 +123,12 @@ object ConversationSpace {             .build()      /** Publish/refresh the long-lived shortcut backing [target]; returns its id. */-    fun pushShortcut(context: Context, target: ConversationTarget): String {+    fun pushShortcut(+        context: Context,+        target: ConversationTarget,+        shareTarget: Boolean = false,+        rank: Int = 0,+    ): String {         val id = shortcutId(target)         val label = (target.title ?: target.personName).ifBlank { context.getString(R.string.app_name) }         val intent = putExtras(@@ -121,18 +137,59 @@ object ConversationSpace {                 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),             target,         )+        val categories = if (shareTarget) {+            setOf(CONVERSATION_CATEGORY, SHARE_TARGET_CATEGORY)+        } else {+            setOf(CONVERSATION_CATEGORY)+        }         val shortcut = ShortcutInfoCompat.Builder(context, id)             .setLongLived(true)             .setShortLabel(label)             .setIntent(intent)             .setPerson(person(context, target))-            .setCategories(setOf(CONVERSATION_CATEGORY))+            .setCategories(categories)+            .setLocusId(LocusIdCompat(id))+            .setRank(rank)             .setIcon(IconCompat.createWithResource(context, R.mipmap.ic_launcher))             .build()         runCatching { ShortcutManagerCompat.pushDynamicShortcut(context, shortcut) }         return id     } +    /**+     * Publish the top [MAX_SHARE_TARGETS] conversations (callers pass them newest-first,+     * as `loadSmsThreadsMerged` returns them) as Direct Share targets, reusing the same+     * shortcut ids / locus ids as the conversation shortcuts so the share sheet, the+     * notifications and the bubbles all name the same conversation.+     *+     * Refreshed whenever the conversation list reloads. A conversation that falls out of+     * the top four is demoted back to a plain conversation shortcut (kept, so its+     * notification/bubble keep working); one that is gone entirely is removed.+     */+    fun publishShareTargets(context: Context, targets: List<ConversationTarget>) {+        val top = targets.distinctBy { shortcutId(it) }.take(MAX_SHARE_TARGETS)+        top.forEachIndexed { index, target ->+            pushShortcut(context, target, shareTarget = true, rank = index)+        }+        val topIds = top.mapTo(HashSet()) { shortcutId(it) }+        runCatching {+            val byId = targets.associateBy { shortcutId(it) }+            ShortcutManagerCompat.getDynamicShortcuts(context)+                .filter { shortcut ->+                    shortcut.categories?.contains(SHARE_TARGET_CATEGORY) == true &&+                        shortcut.id !in topIds+                }+                .forEach { stale ->+                    val target = byId[stale.id]+                    if (target != null) {+                        pushShortcut(context, target, shareTarget = false)+                    } else {+                        ShortcutManagerCompat.removeLongLivedShortcuts(context, listOf(stale.id))+                    }+                }+        }+    }+     /** Remove the shortcut for [target] (e.g. when a conversation is deleted). */     fun removeShortcut(context: Context, target: ConversationTarget) {         runCatching { ShortcutManagerCompat.removeLongLivedShortcuts(context, listOf(shortcutId(target))) }
communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.ktindex 97c0349bc0..141716d316 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/CommunicateNavGraph.kt@@ -39,6 +39,9 @@ fun EntryProviderScope<Route>.coreEntries(backStack: NavBackStack<Route>) {     entry<Route.Messages>(metadata = ListPage() + SiblingPage()) {         MessagesScreen(             onOpenThread = { thread ->+                // A picker share (regular share target, no conversation chosen)+                // seeds the first thread opened after it; consume so later opens are plain.+                val pendingShare = com.vayunmathur.communicate.intents.PendingShare.consume()                 val route = Route.Conversation(                     threadId = thread.threadId,                     address = thread.address,@@ -48,6 +51,8 @@ fun EntryProviderScope<Route>.coreEntries(backStack: NavBackStack<Route>) {                     isGroup = thread.isGroup,                     participants = thread.participants,                     groupTitle = thread.groupTitle,+                    sharedText = pendingShare?.body,+                    sharedAttachmentUris = pendingShare?.sharedAttachmentUris.orEmpty(),                 )                 // Re-tapping another thread replaces the detail instead of stacking                 // Conversation on Conversation.@@ -223,6 +228,8 @@ fun EntryProviderScope<Route>.conversationEntries(backStack: NavBackStack<Route>             isGroup = route.isGroup,             participants = route.participants,             groupTitle = route.groupTitle,+            initialDraft = route.sharedText.orEmpty(),+            initialAttachmentUris = route.sharedAttachmentUris,             onBack = { backStack.pop() },             onOpenRcsVerify = { peer -> backStack.add(Route.RcsVerify(peer)) },             onOpenRcsGroupMembers = { cid -> backStack.add(Route.RcsGroupMembers(cid)) },
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 cd86603b02..d5a20da2a7 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -1,9 +1,13 @@ package com.vayunmathur.communicate.ui  import android.Manifest+import android.content.Context import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts+import androidx.core.content.ContextCompat import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue@@ -49,6 +53,9 @@ fun ConversationScreen(     isGroup: Boolean = false,     participants: List<String> = emptyList(),     groupTitle: String? = null,+    /** Shared text/attachments seeding the composer (Direct Share); empty for a plain open. */+    initialDraft: String = "",+    initialAttachmentUris: List<String> = emptyList(),     onBack: () -> Unit,     onOpenRcsVerify: (String) -> Unit = {}, onOpenRcsGroupMembers: (String) -> Unit = {}, ) {@@ -60,8 +67,50 @@ fun ConversationScreen(     val pollSendFailedMessage = stringResource(R.string.poll_send_failed)     val safetyNumberFailedMessage = stringResource(R.string.signal_safety_number_accept_failed)     val scope = rememberCoroutineScope()-    var draft by remember(threadId) { mutableStateOf("") }-    var selectedAttachments by remember(threadId) { mutableStateOf<List<CommunicateAttachment>>(emptyList()) }+    // Contextual notification ask (todo/files pattern: system request only at first+    // use, never on first frame): after the first successful send the user has shown+    // messages matter to them, so ask once there and persist that we asked.+    val notificationsLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission(),+    ) {}+    val askNotificationsOnce = remember(context) {+        {+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                val prefs = context.getSharedPreferences(+                    "communicate_notifications", Context.MODE_PRIVATE,+                )+                if (!prefs.getBoolean("has_asked_notifications", false)) {+                    prefs.edit().putBoolean("has_asked_notifications", true).apply()+                    if (ContextCompat.checkSelfPermission(+                            context, Manifest.permission.POST_NOTIFICATIONS,+                        ) != PackageManager.PERMISSION_GRANTED+                    ) {+                        notificationsLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+                    }+                }+            }+        }+    }+    var draft by remember(threadId, initialDraft) { mutableStateOf(initialDraft) }+    var selectedAttachments by remember(threadId, initialAttachmentUris) {+        mutableStateOf(+            initialAttachmentUris.mapNotNull { uriString ->+                runCatching {+                    val uri = android.net.Uri.parse(uriString)+                    runCatching {+                        context.contentResolver.takePersistableUriPermission(+                            uri, Intent.FLAG_GRANT_READ_URI_PERMISSION,+                        )+                    }+                    CommunicateAttachment(+                        contentUri = uriString,+                        mimeType = context.contentResolver.getType(uri) ?: "application/octet-stream",+                        fileName = displayNameOf(context, uri),+                    )+                }.getOrNull()+            },+        )+    }     // Bumped after a send to re-fetch the thread.     var refresh by remember(threadId) { mutableIntStateOf(0) }     val lineChoices = rememberLineChoices()@@ -244,6 +293,7 @@ fun ConversationScreen(                             participants = if (isGroup) participants else emptyList(),                         )                         if (ok) {+                            askNotificationsOnce()                             // Clear only what was sent; anything the user                             // typed or attached while sending survives.                             if (draft == sentDraft) draft = ""
communicate/src/main/java/com/vayunmathur/communicate/ui/DeepLinkEffect.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/DeepLinkEffect.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/DeepLinkEffect.ktindex df0cac7d16..ff77cfd388 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/DeepLinkEffect.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/DeepLinkEffect.kt@@ -6,6 +6,7 @@ import androidx.compose.ui.res.stringResource import com.vayunmathur.communicate.R import com.vayunmathur.communicate.Route import com.vayunmathur.communicate.intents.DeepLink+import com.vayunmathur.communicate.intents.PendingShare import com.vayunmathur.library.util.NavBackStack  /** Deep links open the conversation they name, including links arriving at a running instance. */@@ -27,8 +28,13 @@ fun DeepLinkEffect(                     subscriptionId = link.subscriptionId,                     isGroup = link.isGroup,                     groupTitle = link.groupTitle,+                    sharedText = link.body,+                    sharedAttachmentUris = link.sharedAttachmentUris,                 ),             )+            // No conversation chosen yet: stay on the list and seed whichever+            // thread the user opens next (consumed in CommunicateNavGraph).+            is DeepLink.SharePicker -> PendingShare.store(link)             is DeepLink.UnsupportedGroupInvite ->                 com.vayunmathur.library.util.AppMessages.show(groupUnsupportedMessage)             null -> Unit
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 592754a421..a8ebd4ef5d 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/MessagesScreen.kt@@ -263,7 +263,35 @@ fun MessagesScreen(onOpenThread: (SmsThread) -> Unit, onOpenAccounts: () -> Unit                     // loading flash on every return from a thread). The                     // denied->granted transition still shows LoadingState first                     // because this content is newly composed (initialValue=null).-                    value = withContext(Dispatchers.IO) { CommunicateRepository.loadSmsThreadsMerged(context) }+                    value = withContext(Dispatchers.IO) {+                        val rows = CommunicateRepository.loadSmsThreadsMerged(context)+                        // Direct Share targets follow the conversation list: the list+                        // reloads on resume / delete / the 15s poll above, so republishing+                        // here (newest-first, capped inside) keeps the share sheet's+                        // direct-share row on the current top conversations.+                        com.vayunmathur.communicate.notifications.ConversationSpace.publishShareTargets(+                            context,+                            rows.map { thread ->+                                com.vayunmathur.communicate.notifications.ConversationTarget(+                                    line = thread.line,+                                    address = thread.address,+                                    remoteId = thread.remoteId,+                                    threadId = thread.threadId,+                                    isGroup = thread.isGroup,+                                    title = if (thread.isGroup) {+                                        thread.groupTitle ?: thread.displayName+                                    } else {+                                        null+                                    },+                                    personName = thread.displayName+                                        ?: thread.groupTitle+                                        ?: thread.address,+                                    subscriptionId = thread.subscriptionId,+                                )+                            },+                        )+                        rows+                    }                 }                  when (val rows = threads.value) {
communicate/src/main/res/xml/shortcuts.xml
diff --git a/communicate/src/main/res/xml/shortcuts.xml b/communicate/src/main/res/xml/shortcuts.xmlnew file mode 100644index 0000000000..6d0a107621--- /dev/null+++ b/communicate/src/main/res/xml/shortcuts.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">+    <!-- Direct Share (system share sheet's direct-share row). The category must+         match ConversationSpace.SHARE_TARGET_CATEGORY: dynamic conversation+         shortcuts carrying that category become chooser targets, and tapping+         one launches MainActivity with the ACTION_SEND / SEND_MULTIPLE intent+         (plus EXTRA_SHORTCUT_ID) declared in its intent-filters. -->+    <share-target android:targetClass="com.vayunmathur.communicate.MainActivity">+        <data android:mimeType="text/plain" />+        <data android:mimeType="image/*" />+        <data android:mimeType="video/*" />+        <data android:mimeType="application/*" />+        <category android:name="com.vayunmathur.communicate.category.DIRECT_SHARE" />+    </share-target>+</shortcuts>
email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSettings.ktindex 0987f88c06..bd4880da69 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSettings.kt@@ -40,10 +40,22 @@ class EmailSettings private constructor(context: Context) {         _loadRemoteImages.value = enabled     } +    private val _hasAskedNotifications =+        MutableStateFlow(prefs.getBoolean(KEY_HAS_ASKED_NOTIFICATIONS, false))++    /** Whether the one-time contextual notification ask has already fired. */+    val hasAskedNotifications: StateFlow<Boolean> = _hasAskedNotifications.asStateFlow()++    fun setHasAskedNotifications() {+        prefs.edit { putBoolean(KEY_HAS_ASKED_NOTIFICATIONS, true) }+        _hasAskedNotifications.value = true+    }+     /** Holds preference keys and defaults for email settings. */     companion object {         private const val PREFS = "email_settings"         private const val KEY_LOAD_REMOTE_IMAGES = "load_remote_images"+        private const val KEY_HAS_ASKED_NOTIFICATIONS = "has_asked_notifications"          @Volatile         private var instance: EmailSettings? = null
email/src/main/java/com/vayunmathur/email/ui/MainContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt b/email/src/main/java/com/vayunmathur/email/ui/MainContent.ktindex b7c585948c..5732c2c967 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt@@ -1,10 +1,20 @@ package com.vayunmathur.email.ui +import android.Manifest+import android.content.pm.PackageManager+import android.os.Build+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.platform.LocalContext+import androidx.core.content.ContextCompat import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.Navigation import com.vayunmathur.email.Route+import com.vayunmathur.email.data.EmailSettings import com.vayunmathur.email.platform.addAccountEntries import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.IntentState@@ -14,6 +24,28 @@ import com.vayunmathur.library.util.rememberNavBackStack @Composable fun MainContent(viewModel: EmailViewModel) {     val accounts by viewModel.accounts.collectAsStateWithLifecycle(emptyList())+    // Contextual notification ask (todo/files pattern: system request only at+    // first use, never on first frame): once a first account exists, mail+    // notifications become relevant, so ask once then and persist that we asked.+    val context = LocalContext.current+    val settings = remember(context) { EmailSettings.get(context) }+    val hasAskedNotifications by settings.hasAskedNotifications.collectAsStateWithLifecycle()+    val notificationsLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission(),+    ) {}+    LaunchedEffect(accounts.isNotEmpty(), hasAskedNotifications) {+        if (accounts.isNotEmpty() && !hasAskedNotifications &&+            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU+        ) {+            settings.setHasAskedNotifications()+            if (ContextCompat.checkSelfPermission(+                    context, Manifest.permission.POST_NOTIFICATIONS,+                ) != PackageManager.PERMISSION_GRANTED+            ) {+                notificationsLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+            }+        }+    }     val navigationRoute = IntentState.navigationRoute     val isEmlViewer = navigationRoute is Route.EmlViewer 
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.ktindex ad8eb0c809..a3e1046bd9 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt@@ -1,13 +1,8 @@ package com.vayunmathur.fooddelivery -import android.Manifest import android.content.Intent-import android.content.pm.PackageManager-import android.os.Build-import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf-import androidx.core.content.ContextCompat import com.stripe.android.PaymentConfiguration import com.vayunmathur.fooddelivery.platform.AppInit import com.vayunmathur.fooddelivery.platform.emailVerificationOrNull@@ -34,9 +29,6 @@ class MainActivity : MaActivity() {      private val verifyEmail = mutableStateOf<Route.EmailVerification?>(null) -    private val requestNotificationPermission =-        registerForActivityResult(ActivityResultContracts.RequestPermission()) { }-         /** Holds the Stripe publishable key used to initialise payments. */     companion object {         private const val STRIPE_PUBLISHABLE_KEY =@@ -51,7 +43,8 @@ class MainActivity : MaActivity() {         openRestaurantId.value = intent.restaurantIdOrNull()         openCheckout.value = intent.isCheckoutDeepLink()         verifyEmail.value = intent.emailVerificationOrNull()-        requestNotificationPermissionIfNeeded()+        // No notification ask here: it moved to order confirmation in+        // CheckoutScreen, where order-tracking notifications become relevant.         // The TLS trust bundle and the saved auth token are warmed up off the main thread by         // AppInit, so nothing here touches the network or disk. @@ -75,10 +68,4 @@ class MainActivity : MaActivity() {         intent.emailVerificationOrNull()?.let { verifyEmail.value = it }     } -    private fun requestNotificationPermissionIfNeeded() {-        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return-        val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==-            PackageManager.PERMISSION_GRANTED-        if (!granted) requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)-    } }
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.ktindex 9ac5eaa648..c587c8af21 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt@@ -1,5 +1,12 @@ package com.vayunmathur.fooddelivery.ui +import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.core.content.ContextCompat import com.vayunmathur.library.log.Log import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column@@ -74,6 +81,25 @@ fun CheckoutScreen(     var error by remember { mutableStateOf<String?>(null) }     var orderSuccess by remember { mutableStateOf(false) }     var checkoutResponse by remember { mutableStateOf<CheckoutResponse?>(null) }+    // Contextual notification ask (todo/files pattern): only when an order is+    // confirmed and tracking starts, ask once and persist that we asked.+    val notificationsLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission(),+    ) {}+    LaunchedEffect(orderSuccess) {+        if (orderSuccess && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+            val prefs = context.getSharedPreferences("fooddelivery_prefs", Context.MODE_PRIVATE)+            if (!prefs.getBoolean("has_asked_notifications", false)) {+                prefs.edit().putBoolean("has_asked_notifications", true).apply()+                if (ContextCompat.checkSelfPermission(+                        context, Manifest.permission.POST_NOTIFICATIONS,+                    ) != PackageManager.PERMISSION_GRANTED+                ) {+                    notificationsLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+                }+            }+        }+    }      var promoCode by remember { mutableStateOf("") }     var customer by remember { mutableStateOf<Customer?>(null) }
taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt b/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.ktindex 7395f8e48f..14c890f5e0 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt@@ -1,13 +1,8 @@ package com.vayunmathur.taxi -import android.Manifest import android.content.Intent-import android.content.pm.PackageManager-import android.os.Build-import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf-import androidx.core.content.ContextCompat import com.vayunmathur.library.image.ImageLoader import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle@@ -37,9 +32,6 @@ class MainActivity : MaActivity() {     // into the running UI.     private val bookingTrip = mutableStateOf<BookingTrip?>(null) -    private val requestNotificationPermission =-        registerForActivityResult(ActivityResultContracts.RequestPermission()) { }-     override fun onCreateBeforeContent() {         NetworkClient.init(this, TrustBundle.STANDARD)         // Driver photos load over HTTP(S) through the shared image pipeline;@@ -52,7 +44,8 @@ class MainActivity : MaActivity() {          trackRideId.value = intent.trackRideIdOrNull()         bookingTrip.value = intent.bookingTripOrNull()-        requestNotificationPermissionIfNeeded()+        // No notification ask here: it moved to booking confirmation in+        // LyftBookingFlow, where ride-tracking notifications become relevant.     }      @Composable@@ -67,13 +60,6 @@ class MainActivity : MaActivity() {         intent.bookingTripOrNull()?.let { bookingTrip.value = it }     } -    private fun requestNotificationPermissionIfNeeded() {-        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return-        val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==-            PackageManager.PERMISSION_GRANTED-        if (!granted) requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)-    }-     private fun Intent.trackRideIdOrNull(): String? =         getStringExtra(RideLiveUpdate.EXTRA_TRACK_RIDE_ID)?.takeIf { it.isNotBlank() } 
taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt b/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.ktindex f693a0c505..41dc25bfa0 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt@@ -1,5 +1,11 @@ package com.vayunmathur.taxi.ui +import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column@@ -25,6 +31,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompat import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.MaterialTheme@@ -80,6 +87,25 @@ fun LyftBookingFlow(     val scope = rememberCoroutineScope()     val provider = remember { LyftProvider(context.applicationContext) }     var step by remember { mutableStateOf<Step>(Step.LoadingPayments) }+    // Contextual notification ask (todo/files pattern): only when a booking is+    // confirmed and ride tracking starts, ask once and persist that we asked.+    val notificationsLauncher = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission(),+    ) {}+    LaunchedEffect(step) {+        if (step is Step.Created && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+            val prefs = context.getSharedPreferences("taxi_notifications", Context.MODE_PRIVATE)+            if (!prefs.getBoolean("has_asked_notifications", false)) {+                prefs.edit().putBoolean("has_asked_notifications", true).apply()+                if (ContextCompat.checkSelfPermission(+                        context, Manifest.permission.POST_NOTIFICATIONS,+                    ) != PackageManager.PERMISSION_GRANTED+                ) {+                    notificationsLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+                }+            }+        }+    }     val noPaymentMessage = stringResource(R.string.booking_no_payment)     val connectPromptMessage = stringResource(R.string.connect_prompt, "Lyft")