Modern Apps git

← Modern-Apps.git

notifications: every notification goes somewhere when tapped

Commit
a54e9f8accd89bf62a3c310465ec55dd146aa7e4
Author
Vayun Mathur <[email protected]>
When
2026-11-20 22:46 UTC (15 days ago)
Parents
ae33599
Dead taps fixed: clock's finished timer, share request/done,
files transfer progress, photos sync (one central fix covers
sync/OCR/face/clip), email/securemail sync services and euicc
downloads (targets LuiActivity - euicc has no MainActivity)
now carry content intents to the right entry point.

Reading cancels: opening an email thread cancels its
notifications (same ids the poster used); opening a
conversation cancels communicate's incoming notification for
it across all lines. Share transfers drop from IMPORTANCE_MAX
to HIGH on a new _v2 channel (requests stay prominent).

Model downloads in library/downloadservice could be deferred
or killed mid-download; the worker now promotes to foreground
with a low-priority progress notification (tap returns to the
host app), and a promotion failure logs and continues rather
than failing the download.

Verified: compile for clock, share, email, communicate,
files, photos, euicc, securemail, downloadservice.

Diff

clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt b/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.ktindex 5fdd4df258..2cb1277617 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/TimerReciever.kt@@ -1,10 +1,12 @@ package com.vayunmathur.clock.platform import android.app.NotificationManager+import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat+import com.vayunmathur.clock.MainActivity import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.clock.data.Timer import com.vayunmathur.clock.R@@ -30,10 +32,21 @@ class TimerReceiver : BroadcastReceiver() {             try {                 nm.cancel(id.hashCode()) +                // Tap opens the app (same pattern as StopwatchNotificationHelper):+                // without a content intent the finished-timer notification was a dead tap.+                val contentIntent = PendingIntent.getActivity(+                    context,+                    id.hashCode(),+                    Intent(context, MainActivity::class.java).apply {+                        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+                    },+                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+                )                 val notification = NotificationCompat.Builder(context, "finished_timers_channel")                     .setSmallIcon(R.drawable.outline_timer_24)                     .setContentTitle(context.getString(R.string.timer_finished_title))                     .setContentText(context.getString(R.string.timer_finished_text, name))+                    .setContentIntent(contentIntent)                     .setPriority(NotificationCompat.PRIORITY_HIGH)                     .setCategory(NotificationCompat.CATEGORY_ALARM)                     .setAutoCancel(true)
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 43bc7632fd..4a703b95e6 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/notifications/ConversationSpace.kt@@ -127,6 +127,38 @@ object ConversationSpace {         runCatching { ShortcutManagerCompat.removeLongLivedShortcuts(context, listOf(shortcutId(target))) }     } +    /**+     * Cancel the incoming-message notification for a conversation, matching the+     * tag/id [notifyIncoming] posted it under (`shortcutId` tag, [MESSAGE_NOTIFICATION_ID]).+     * Called when the conversation is opened: the tapped notification auto-cancels+     * itself, but opening from the list (or a second message replacing the first+     * under the same tag) leaves it in the shade until cancelled here.+     */+    fun cancelIncoming(context: Context, target: ConversationTarget) {+        val nm = context.getSystemService(NotificationManager::class.java) ?: return+        runCatching { nm.cancel(shortcutId(target), MESSAGE_NOTIFICATION_ID) }+    }++    /** [cancelIncoming] from the primitives a conversation screen already holds. */+    fun cancelIncoming(+        context: Context,+        line: CommunicateLine,+        address: String,+        remoteId: String? = null,+        threadId: Long = -1L,+    ) {+        cancelIncoming(+            context,+            ConversationTarget(+                line = line,+                address = address,+                remoteId = remoteId,+                threadId = threadId,+                personName = address,+            ),+        )+    }+     /**      * Post a conversation-style notification for an inbound message, pushing the backing shortcut and      * attaching bubble metadata first so the system can surface it in the conversations section.
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.ktindex e00c6c3232..fe515ecabc 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationReadEffects.kt@@ -15,6 +15,7 @@ import com.vayunmathur.communicate.data.markSignalRead import com.vayunmathur.communicate.data.markSimThreadRead import com.vayunmathur.communicate.data.markWhatsAppRead import com.vayunmathur.communicate.data.updateGoogleVoiceThread+import com.vayunmathur.communicate.notifications.ConversationSpace  /**  * Per-line side effects for an open conversation: mark-read dispatch plus the@@ -33,6 +34,11 @@ fun ConversationReadEffects(     address: String,     onRefreshTick: () -> Unit, ) {+    // Cancel-on-read: opening the conversation clears its notification from the shade,+    // matching the tag/id ConversationSpace.notifyIncoming posted it under.+    LaunchedEffect(line, remoteId, threadId, address) {+        ConversationSpace.cancelIncoming(context, line, address, remoteId, threadId)+    }     // Opening a SIM thread clears the provider's unread flags. Nothing else writes them back, and     // the badge is recomputed from the provider, so imported rows would stay unread forever (#562).     LaunchedEffect(threadId, line) {
euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt b/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.ktindex 04757119f6..d8af3f3cb2 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/service/DownloadService.kt@@ -3,6 +3,7 @@ package com.vayunmathur.euicc.service import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager+import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent@@ -12,6 +13,7 @@ import android.os.IBinder import android.os.PowerManager import androidx.core.app.NotificationCompat import com.vayunmathur.euicc.R+import com.vayunmathur.euicc.platform.LuiActivity import java.util.concurrent.atomic.AtomicBoolean  /**@@ -47,9 +49,21 @@ class DownloadService : Service() {             acquire(WAKE_LOCK_TIMEOUT_MS)         }         ensureChannel()+        // Tap opens the app. euicc has no MainActivity (deliberately no launcher+        // activity): LuiActivity is the single home-screen entry, showing the same+        // Navigation/Home, so it is the tap target here.+        val contentIntent = PendingIntent.getActivity(+            this,+            FOREGROUND_ID,+            Intent(this, LuiActivity::class.java).apply {+                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)+            },+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )         val notification = NotificationCompat.Builder(this, CHANNEL_ID)             .setContentTitle(getString(R.string.installing_title))             .setContentText(getString(R.string.installing_text))+            .setContentIntent(contentIntent)             .setSmallIcon(android.R.drawable.stat_sys_download)             .setOngoing(true)             .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, true)
files/src/main/java/com/vayunmathur/files/platform/ProgressNotificationWorker.kt
diff --git a/files/src/main/java/com/vayunmathur/files/platform/ProgressNotificationWorker.kt b/files/src/main/java/com/vayunmathur/files/platform/ProgressNotificationWorker.ktindex e9eddadf8e..15641fa587 100644--- a/files/src/main/java/com/vayunmathur/files/platform/ProgressNotificationWorker.kt+++ b/files/src/main/java/com/vayunmathur/files/platform/ProgressNotificationWorker.kt@@ -1,13 +1,16 @@ package com.vayunmathur.files.platform import android.app.NotificationChannel import android.app.NotificationManager+import android.app.PendingIntent import android.content.Context+import android.content.Intent import android.content.pm.ServiceInfo import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import androidx.work.CoroutineWorker import androidx.work.ForegroundInfo import androidx.work.WorkerParameters+import com.vayunmathur.files.MainActivity import com.vayunmathur.files.R  /**@@ -42,13 +45,24 @@ abstract class ProgressNotificationWorker(         )     } -    private fun buildNotification(progress: Int) =-        NotificationCompat.Builder(applicationContext, channelId)+    private fun buildNotification(progress: Int): android.app.Notification {+        // Tap opens the app: the ongoing foreground notification was a dead tap before.+        val contentIntent = PendingIntent.getActivity(+            applicationContext,+            notificationId,+            Intent(applicationContext, MainActivity::class.java).apply {+                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+            },+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        return NotificationCompat.Builder(applicationContext, channelId)             .setContentTitle(applicationContext.getString(contentTitleRes))+            .setContentIntent(contentIntent)             .setSmallIcon(R.drawable.folder_24px)             .setProgress(FULL_PROGRESS, progress, false)             .setOngoing(true)             .build()+    }      protected fun createForegroundInfo(progress: Int) =         ForegroundInfo(
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.ktindex 4d1eec2577..88c0ae86b3 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt@@ -1,17 +1,25 @@ package com.vayunmathur.library.downloadservice +import android.app.NotificationManager+import android.app.PendingIntent import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import androidx.core.app.NotificationCompat import androidx.work.BackoffPolicy import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.Data import androidx.work.ExistingWorkPolicy+import androidx.work.ForegroundInfo import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.ensureNotificationChannel import java.io.File import java.io.IOException import java.util.concurrent.TimeUnit@@ -26,10 +34,12 @@ import kotlinx.coroutines.CancellationException  * those, and a failed run is retried by WorkManager with exponential backoff instead of being  * swallowed.  *- * This is a plain background worker, so the platform stops it after roughly ten minutes of- * execution. That is fine because the work is resumable: partial bytes live in `<fileName>.part`- * and the next run continues with a `Range` request, so a large bundle completes across several- * runs. Promote it to a foreground worker (`setForeground`) if it needs to finish in one pass.+ * This is a foreground worker: [doWork] calls `setForeground` with a LOW progress+ * notification so a large bundle can finish in one pass instead of being stopped+ * after roughly ten minutes of background execution. The work stays resumable+ * regardless — partial bytes live in `<fileName>.part` and a later run continues+ * with a `Range` request — so a foreground promotion failure (or the platform+ * reclaiming the service) degrades to the old multi-run behaviour, not data loss.  */ class ModelDownloadWorker(context: Context, params: WorkerParameters) :     CoroutineWorker(context, params) {@@ -43,6 +53,16 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :         val specs = readSpecs(inputData)         if (specs.isEmpty()) return Result.failure() +        // Foreground promotion (see class doc): a failure here must not fail the+        // download — the resumable background path still completes it across runs.+        try {+            setForeground(createForegroundInfo(specs))+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            Log.status(TAG, "could not promote to foreground; continuing in background", e)+        }+         val targetDir = inputData.getString(KEY_TARGET_DIR)?.let(::File)         val ds = DataStoreUtils.getInstance(applicationContext)         return try {@@ -64,8 +84,63 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :         }     } +    /**+     * LOW, indeterminate progress notification for the foreground promotion.+     *+     * Kept local to downloadservice: this library has no host `MainActivity` to+     * target, so the tap intent is the hosting app's launcher intent+     * (`getLaunchIntentForPackage`), falling back to no content intent when the+     * host has no launcher entry. Indeterminate because [runDownloadsCore]+     * reports no per-byte progress to the worker.+     */+    private fun createForegroundInfo(specs: List<DownloadSpec>): ForegroundInfo {+        applicationContext.ensureNotificationChannel(+            id = CHANNEL_ID,+            name = applicationContext.getString(R.string.downloading),+            importance = NotificationManager.IMPORTANCE_LOW,+            description = applicationContext.getString(+                R.string.downloading_required_components_for_this+            ),+        )+        val launchIntent = applicationContext.packageManager+            .getLaunchIntentForPackage(applicationContext.packageName)+            ?.apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP }+        val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)+            .setSmallIcon(android.R.drawable.stat_sys_download)+            .setContentTitle(applicationContext.getString(R.string.downloading))+            .setContentText(+                specs.firstOrNull()?.description+                    ?: applicationContext.getString(R.string.downloading_required_components_for_this)+            )+            .setProgress(0, 0, true)+            .setOngoing(true)+            .setOnlyAlertOnce(true)+        if (launchIntent != null) {+            builder.setContentIntent(+                PendingIntent.getActivity(+                    applicationContext,+                    NOTIFICATION_ID,+                    launchIntent,+                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+                )+            )+        }+        val foregroundInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+            ForegroundInfo(+                NOTIFICATION_ID,+                builder.build(),+                ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC,+            )+        } else {+            ForegroundInfo(NOTIFICATION_ID, builder.build())+        }+        return foregroundInfo+    }+     /** WorkManager input keys, enqueue entry points and spec decoding for [ModelDownloadWorker]. */     companion object {+        private const val CHANNEL_ID = "model_downloads"+        private const val NOTIFICATION_ID = 9101         private const val TAG = "ModelDownloadWorker"         private const val KEY_URLS = "urls"         private const val KEY_FILE_NAMES = "fileNames"
securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.ktindex 4f13e5daba..23b5014363 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/service/MailSocketService.kt@@ -71,9 +71,19 @@ class MailSocketService : Service() {     }      private fun buildNotification(): android.app.Notification {+        // Tap opens the app: the ongoing foreground notification was a dead tap before.+        val contentIntent = android.app.PendingIntent.getActivity(+            this,+            NOTIFICATION_ID,+            Intent(this, com.vayunmathur.securemail.MainActivity::class.java).apply {+                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+            },+            android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE,+        )         val builder = androidx.core.app.NotificationCompat.Builder(this, CHANNEL_ID)             .setContentTitle("SecureMail relay")             .setContentText("Listening for encrypted mail")+            .setContentIntent(contentIntent)             .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)             .setOngoing(true)         return builder.build()
share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.ktindex 6b02bbd67b..b46714ea9c 100644--- a/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/receive/ShareReceiveNotifier.kt@@ -37,22 +37,28 @@ private const val TAG = "ShareNotifier" /**  * Everything the user is meant to react to — requests, progress, and outcomes.  *- * Both `IMPORTANCE_MAX`, so all of them heads-up rather than sitting in the shade. The only- * quiet notification `:share` posts is the foreground service's own "Ready to receive", which- * has its own `IMPORTANCE_LOW` channel in [ShareTransferService]; the two are deliberately- * separate so silencing the always-on status indicator does not silence an incoming transfer.+ * Requests are `IMPORTANCE_MAX`, so they heads-up rather than sitting in the shade; transfers+ * are `IMPORTANCE_HIGH` (see [CHANNEL_TRANSFERS]). The only quiet notification `:share` posts+ * is the foreground service's own "Ready to receive", which has its own `IMPORTANCE_LOW`+ * channel in [ShareTransferService]; the two are deliberately separate so silencing the+ * always-on status indicator does not silence an incoming transfer.  *  * [CHANNEL_REQUESTS] carries a `_v2` suffix because the first cut of it was `IMPORTANCE_HIGH`,  * and a channel's importance is fixed for good: `createNotificationChannel` refreshes a  * channel's name and description, but the system ignores any later change to its importance  * and remembers the settings of deleted channels, so raising it needs a new id.+ * [CHANNEL_TRANSFERS] follows the same precedent: it was `IMPORTANCE_MAX`, so lowering it+ * to `IMPORTANCE_HIGH` needs the new `_v2` id and deletion of the old channel.  */ private const val CHANNEL_REQUESTS = "share_requests_v2"-private const val CHANNEL_TRANSFERS = "share_transfers"+private const val CHANNEL_TRANSFERS = "share_transfers_v2"  /** The `IMPORTANCE_HIGH` requests channel that [CHANNEL_REQUESTS] replaces. */ private const val CHANNEL_LEGACY_REQUESTS = "share_requests" +/** The `IMPORTANCE_MAX` transfers channel that [CHANNEL_TRANSFERS] replaces. */+private const val CHANNEL_LEGACY_TRANSFERS = "share_transfers"+ /** Concurrent transfers bundle under one summary instead of stacking. */ private const val GROUP_KEY = "com.vayunmathur.share.TRANSFERS" @@ -89,11 +95,12 @@ private const val HASH_MULTIPLIER = 31 private const val MAX_PREVIEW_PX = 1024  /**- * Request codes reserved per notification, so Share and Save cannot collide.+ * Request codes reserved per notification, so Share, Save and the body tap cannot collide.  *- * Two per notification id: `id * N` for Share and `id * N + 1` for Save.+ * Three per notification id: `id * N` for Share, `id * N + 1` for Save and+ * `id * N + 2` for the content (body-tap) intent.  */-private const val REQUEST_CODES_PER_NOTIF = 2+private const val REQUEST_CODES_PER_NOTIF = 3  /**  * Turns incoming transfers — Quick Share and AirDrop alike — into notifications, which are the@@ -145,6 +152,7 @@ class ShareReceiveNotifier(      private fun ensureChannels() {         appContext.deleteNotificationChannel(CHANNEL_LEGACY_REQUESTS)+        appContext.deleteNotificationChannel(CHANNEL_LEGACY_TRANSFERS)         appContext.ensureNotificationChannel(             id = CHANNEL_REQUESTS,             name = appContext.getString(R.string.share_channel_requests_name),@@ -154,11 +162,27 @@ class ShareReceiveNotifier(         appContext.ensureNotificationChannel(             id = CHANNEL_TRANSFERS,             name = appContext.getString(R.string.share_channel_transfers_name),-            importance = NotificationManager.IMPORTANCE_MAX,+            importance = NotificationManager.IMPORTANCE_HIGH,             description = appContext.getString(R.string.share_channel_transfers_desc),         )     } +    /**+     * Body-tap intent opening the app. Request and Done notifications carried only+     * action buttons before, so tapping the body itself was a dead tap.+     */+    private fun mainActivityIntent(notifId: Int): PendingIntent {+        val intent = Intent(appContext, com.vayunmathur.share.MainActivity::class.java).apply {+            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+        }+        return PendingIntent.getActivity(+            appContext,+            notifId * REQUEST_CODES_PER_NOTIF + 2,+            intent,+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+        )+    }+     private suspend fun watch() {         coroutineScope {             val children = mutableMapOf<Long, Job>()@@ -285,6 +309,7 @@ class ShareReceiveNotifier(         return base(CHANNEL_REQUESTS)             .setContentTitle(conn.displayName)             .setContentText(text)+            .setContentIntent(mainActivityIntent(id))             .setCategory(NotificationCompat.CATEGORY_SOCIAL)             .setOngoing(true)             .setTimeoutAfter(REQUEST_TIMEOUT_MS)@@ -347,6 +372,7 @@ class ShareReceiveNotifier(             .setContentText(                 appContext.resources.getQuantityString(R.plurals.share_received_count, received.size, received.size),             )+            .setContentIntent(mainActivityIntent(id))             .setAutoCancel(true)         previewBitmap(received)?.let { preview ->             // `bigLargeIcon(null)` so expanding drops the thumbnail instead of showing the same