Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Mirror Android notifications to paired PCs

Bee4c70ef4776fc
diff --git a/README.md b/README.md
index 662e4f7..7bd33a2 100644
--- a/README.md
+++ b/README.md
@@ -70,6 +70,10 @@ place and tested; the user-facing features of Phase 1 come next.
power level.
- **Find my device** in both directions. The phone rings on the alarm stream,
even in silent mode.
+- **Notifications** from the phone on the PC, as Windows notifications and in
+ a feed in the app, with the app's icon. Reply inline, run their actions
+ (such as "Mark as read") or dismiss them from the PC; what's cleared on one
+ side is cleared on the other.
- **Capability matrix**: both apps compute which features work for a pair of
devices and what would enable the rest, so the interface never offers
something that can't work.
@@ -81,8 +85,8 @@ place and tested; the user-facing features of Phase 1 come next.
connection service, and an identity key protected by the Android Keystore.
- **Command-line client** for development and testing (`nectarlink`).
-**Next (Phase 1)**: notifications with replies, clipboard, file transfer, media
-controls, and a Windows installer. Mirroring, messages, calls and the other
+**Next (Phase 1)**: clipboard, file transfer, media controls, notification
+filters and history, and a Windows installer. Mirroring, messages, calls and the other
features in the plan follow in later phases.
## Screenshots
diff --git a/android/README.md b/android/README.md
index 4931863..b71b438 100644
--- a/android/README.md
+++ b/android/README.md
@@ -34,6 +34,10 @@ sources; nothing generated is checked in except the theme tokens
encrypts the identity key with a non-exportable Android Keystore key;
`Ringer` rings on the alarm stream; battery and network monitors feed the
core (Android doesn't let native code watch the network).
+- `notifications/`: the notification listener (with the user's notification
+ access) that hands notifications to the core for mirroring, and reads them
+ (messaging-style content, actions, app icons); replies and actions from a
+ PC run through `core/PhonePlatform`.
- `service/ConnectionService`: a "connected device" foreground service that
keeps the phone reachable and holds the Wi-Fi multicast lock local
discovery needs.
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 83b9372..7d0ffab 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -47,6 +47,17 @@
</intent-filter>
</activity>
+ <!-- Mirroring notifications to PCs; the user grants access in Settings. -->
+ <service
+ android:name=".notifications.NotificationListener"
+ android:exported="true"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
+ <intent-filter>
+ <action android:name="android.service.notification.NotificationListenerService" />
+ </intent-filter>
+ </service>
+
<service
android:name=".service.ConnectionService"
android:exported="false"
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 1146348..263b74d 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -3,19 +3,23 @@ package app.nectarlink.android.core
import android.content.Context
import android.net.wifi.WifiManager
+import android.service.notification.NotificationListenerService
import android.util.Log
import app.nectarlink.android.BuildConfig
+import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.core.Event
import app.nectarlink.core.EventListener
import app.nectarlink.core.NectarlinkException
import app.nectarlink.core.NectarlinkNode
import app.nectarlink.core.NodeOptions
+import app.nectarlink.core.Notification
import app.nectarlink.core.PairingFailure
import app.nectarlink.core.PowerLevel
import app.nectarlink.core.initLogging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
+import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -34,6 +38,12 @@ import kotlinx.coroutines.launch
class Core(context: Context, private val scope: CoroutineScope) : EventListener {
private val context = context.applicationContext
private val ringer = Ringer(this.context)
+ private val platform = PhonePlatform(this.context, ringer)
+ /**
+ * Notification changes, in order: a removal must never overtake the post
+ * it removes. Runs once the node is up.
+ */
+ private val notificationOps = Channel<suspend (NectarlinkNode) -> Unit>(Channel.UNLIMITED)
private val _state = MutableStateFlow(CoreState())
private val _messages = MutableSharedFlow<String>(extraBufferCapacity = 8)
private var node: NectarlinkNode? = null
@@ -77,7 +87,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
awayMode = false,
)
val started = try {
- NectarlinkNode.start(options, ringer, KeystoreKeyProtector(), this@Core)
+ NectarlinkNode.start(options, platform, KeystoreKeyProtector(), this@Core)
} catch (e: NectarlinkException) {
Log.e(TAG, "core failed to start", e)
_state.update { it.copy(status = CoreStatus.Failed(e.message ?: e.javaClass.simpleName)) }
@@ -90,6 +100,46 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
battery.start()
network.start()
}
+ scope.launch {
+ for (op in notificationOps) {
+ runCatching { op(started) }.onFailure { Log.w(TAG, "notification update failed", it) }
+ }
+ }
+ }
+ }
+
+ // ---- Notifications (from NotificationListener) ----
+
+ /**
+ * The notification listener connected (with what's showing now) or lost
+ * access. What this phone offers PCs follows.
+ */
+ fun notificationAccessChanged(granted: Boolean, showing: List<Notification>) {
+ _state.update { it.copy(notificationAccess = granted) }
+ notificationOps.trySend { node ->
+ node.updatePower(PowerLevel.BASIC, if (granted) NOTIFICATION_CAPABILITIES else emptyList())
+ node.notificationsReset(showing)
+ }
+ }
+
+ fun notificationPosted(notification: Notification) {
+ notificationOps.trySend { it.notificationPosted(notification) }
+ }
+
+ fun notificationRemoved(key: String) {
+ notificationOps.trySend { it.notificationRemoved(key) }
+ }
+
+ /**
+ * Re-checks notification access (the user may have changed it in
+ * Settings) and asks Android to reconnect the listener if it's allowed
+ * but not running.
+ */
+ fun refreshNotificationAccess() {
+ val granted = NotificationListener.hasAccess(context)
+ _state.update { it.copy(notificationAccess = granted) }
+ if (granted && NotificationListener.instance == null) {
+ NotificationListenerService.requestRebind(NotificationListener.component(context))
}
}
@@ -192,5 +242,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
private companion object {
const val TAG = "Nectarlink"
+ /** Offered while notification access is granted (docs/protocol/capabilities.md). */
+ val NOTIFICATION_CAPABILITIES = listOf("notify.mirror", "notify.reply")
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
index f88d964..73a1c1e 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
@@ -55,6 +55,8 @@ data class CoreState(
val pairing: PairingState = PairingState.Idle,
/** Name of the device making this phone ring, or null. */
val ringingFrom: String? = null,
+ /** Whether the user let Nectarlink read notifications (to mirror them). */
+ val notificationAccess: Boolean = false,
) {
fun device(id: String): Device? = devices.firstOrNull { it.id == id }
@@ -90,6 +92,8 @@ data class CoreState(
// don't open the pairing screen.
is Event.PairingFailed ->
if (pairing == PairingState.Idle) this else copy(pairing = PairingState.Failed(event.failure))
+ // PCs don't send notifications; nothing for the phone to show.
+ is Event.NotificationsReset, is Event.NotificationPosted, is Event.NotificationRemoved -> this
}
private fun update(id: String, change: (Device) -> Device): CoreState =
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
new file mode 100644
index 0000000..2be3ebc
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.core
+
+import android.app.ActivityOptions
+import android.app.PendingIntent
+import android.app.RemoteInput
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.os.Bundle
+import app.nectarlink.android.notifications.NotificationListener
+import app.nectarlink.core.NotificationFailure
+import app.nectarlink.core.Platform
+
+/**
+ * What the core asks of the phone: ring it, and act on its notifications
+ * for a PC (dismiss, reply, run an action).
+ */
+internal class PhonePlatform(context: Context, private val ringer: Ringer) : Platform {
+ private val context = context.applicationContext
+
+ override fun startRinging() = ringer.startRinging()
+
+ override fun stopRinging() = ringer.stopRinging()
+
+ override fun dismissNotification(key: String) {
+ val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()
+ listener.dismiss(key)
+ }
+
+ override fun runNotificationAction(key: String, action: String, reply: String?) {
+ val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()
+ val sbn = listener.find(key) ?: throw NotificationFailure.NotFound()
+ val target = action.toIntOrNull()?.let { sbn.notification.actions?.getOrNull(it) }
+ ?: throw NotificationFailure.NotFound()
+ val intent = target.actionIntent ?: throw NotificationFailure.NotFound()
+
+ // A reply goes to the app the way the notification shade sends it:
+ // the text as the result of the action's free-form input.
+ val fillIn = Intent()
+ if (reply != null) {
+ val inputs = target.remoteInputs.orEmpty().filter { it.allowFreeFormInput }
+ if (inputs.isEmpty()) throw NotificationFailure.NotFound()
+ val results = Bundle().apply { inputs.forEach { putCharSequence(it.resultKey, reply) } }
+ RemoteInput.addResultsToIntent(inputs.toTypedArray(), fillIn, results)
+ RemoteInput.setResultsSource(fillIn, RemoteInput.SOURCE_FREE_FORM_INPUT)
+ }
+ try {
+ intent.send(context, 0, fillIn, null, null, null, sendOptions())
+ } catch (e: PendingIntent.CanceledException) {
+ throw NotificationFailure.NotFound()
+ }
+ }
+
+ /** Lets an action open its app's screen, as tapping it on the phone would. */
+ private fun sendOptions(): Bundle? {
+ val mode = when {
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA -> ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> {
+ @Suppress("DEPRECATION")
+ ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
+ }
+ else -> return null
+ }
+ return ActivityOptions.makeBasic().setPendingIntentBackgroundActivityStartMode(mode).toBundle()
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.kt
index bebe320..3f92086 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.kt
@@ -11,23 +11,22 @@ import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.os.Build
-import app.nectarlink.core.Platform
/**
* "Find my phone": plays the alarm sound on the alarm stream (audible even
* when the ringer is silent) and vibrates, until stopped or for a minute.
*/
-class Ringer(context: Context) : Platform {
+class Ringer(context: Context) {
private val context = context.applicationContext
private val main = Handler(Looper.getMainLooper())
private var player: MediaPlayer? = null
private val timeout = Runnable { stopRingingNow() }
- override fun startRinging() {
+ fun startRinging() {
main.post { startRingingNow() }
}
- override fun stopRinging() {
+ fun stopRinging() {
main.post { stopRingingNow() }
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt
new file mode 100644
index 0000000..fb0e51b
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationListener.kt
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.notifications
+
+import android.content.ComponentName
+import android.content.Context
+import android.service.notification.NotificationListenerService
+import android.service.notification.StatusBarNotification
+import androidx.core.app.NotificationManagerCompat
+import app.nectarlink.android.NectarlinkApplication
+
+/**
+ * Hands this phone's notifications to the core, which mirrors them to the
+ * PCs the user allows (docs/protocol/notifications.md), and carries out
+ * what a PC asks for: dismissing, replying, running actions.
+ *
+ * Runs only while the user has granted notification access; Android binds
+ * it (and keeps the process alive) for as long as that lasts.
+ */
+class NotificationListener : NotificationListenerService() {
+ private val core get() = (application as NectarlinkApplication).core
+ private val reader by lazy { NotificationReader(this) }
+
+ /** Keys already sent, so an update that shouldn't alert again doesn't. */
+ private val sent = mutableSetOf<String>()
+
+ override fun onListenerConnected() {
+ instance = this
+ sent.clear()
+ val items = activeNotifications.orEmpty().mapNotNull { reader.read(it, currentRanking, update = false) }
+ sent += items.map { it.key }
+ core.notificationAccessChanged(true, items)
+ }
+
+ override fun onListenerDisconnected() {
+ if (instance === this) instance = null
+ core.notificationAccessChanged(false, emptyList())
+ }
+
+ override fun onNotificationPosted(sbn: StatusBarNotification, rankingMap: RankingMap?) {
+ val notification = reader.read(sbn, rankingMap, update = sbn.key in sent)
+ if (notification == null) {
+ // Something we mirrored may have turned into something we don't
+ // (e.g. it became ongoing); take it away on the PC.
+ if (sent.remove(sbn.key)) core.notificationRemoved(sbn.key)
+ return
+ }
+ sent += sbn.key
+ core.notificationPosted(notification)
+ }
+
+ override fun onNotificationRemoved(sbn: StatusBarNotification) {
+ if (sent.remove(sbn.key)) core.notificationRemoved(sbn.key)
+ }
+
+ override fun onDestroy() {
+ if (instance === this) instance = null
+ super.onDestroy()
+ }
+
+ /** What a PC asks for, on the listener that's connected now. */
+ internal fun dismiss(key: String) = cancelNotification(key)
+
+ internal fun find(key: String): StatusBarNotification? =
+ runCatching { getActiveNotifications(arrayOf(key)) }.getOrNull()?.firstOrNull()
+
+ companion object {
+ /** The connected listener, if notification access is granted. */
+ @Volatile
+ internal var instance: NotificationListener? = null
+ private set
+
+ /** Whether the user granted notification access to this app. */
+ fun hasAccess(context: Context): Boolean =
+ NotificationManagerCompat.getEnabledListenerPackages(context).contains(context.packageName)
+
+ fun component(context: Context) = ComponentName(context, NotificationListener::class.java)
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt
new file mode 100644
index 0000000..b9c280f
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/notifications/NotificationReader.kt
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.notifications
+
+import android.app.Notification
+import android.app.NotificationManager
+import android.content.Context
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.service.notification.NotificationListenerService.Ranking
+import android.service.notification.NotificationListenerService.RankingMap
+import android.service.notification.StatusBarNotification
+import android.util.LruCache
+import androidx.core.app.NotificationCompat
+import androidx.core.graphics.drawable.toBitmap
+import java.io.ByteArrayOutputStream
+import app.nectarlink.core.Notification as Mirrored
+import app.nectarlink.core.NotificationAction as MirroredAction
+
+/**
+ * Turns Android notifications into what Nectarlink mirrors, and decides
+ * which ones are worth mirroring at all.
+ */
+internal class NotificationReader(private val context: Context) {
+ private val packages: PackageManager = context.packageManager
+ private val icons = LruCache<String, ByteArray>(48)
+ private val names = LruCache<String, String>(128)
+
+ /** `null` when this notification isn't mirrored. */
+ fun read(sbn: StatusBarNotification, ranking: RankingMap?, update: Boolean): Mirrored? {
+ if (!shouldMirror(sbn)) return null
+ val n = sbn.notification
+ val content = content(n) ?: return null
+ val silent = isSilent(sbn, ranking) || (update && n.flags and Notification.FLAG_ONLY_ALERT_ONCE != 0)
+ return Mirrored(
+ key = sbn.key,
+ app = sbn.packageName,
+ appName = appName(sbn.packageName),
+ title = content.title,
+ text = content.text,
+ sub = content.sub,
+ `when` = sbn.postTime,
+ actions = actions(n),
+ silent = silent,
+ icon = icon(sbn.packageName),
+ )
+ }
+
+ private fun shouldMirror(sbn: StatusBarNotification): Boolean {
+ val n = sbn.notification
+ val skipped = Notification.FLAG_ONGOING_EVENT or Notification.FLAG_FOREGROUND_SERVICE or
+ Notification.FLAG_GROUP_SUMMARY or Notification.FLAG_LOCAL_ONLY
+ return sbn.packageName != context.packageName &&
+ sbn.isClearable &&
+ n.flags and skipped == 0 &&
+ // Media players and progress bars get their own features.
+ n.category != Notification.CATEGORY_TRANSPORT &&
+ n.category != Notification.CATEGORY_PROGRESS &&
+ !n.extras.containsKey(Notification.EXTRA_MEDIA_SESSION)
+ }
+
+ private fun isSilent(sbn: StatusBarNotification, ranking: RankingMap?): Boolean {
+ val r = Ranking()
+ if (ranking == null || !ranking.getRanking(sbn.key, r)) return false
+ return r.importance < NotificationManager.IMPORTANCE_DEFAULT
+ }
+
+ private data class Content(val title: String?, val text: String?, val sub: String?)
+
+ /** Title and text, from a conversation's last message when there is one. */
+ private fun content(n: Notification): Content? {
+ val extras = n.extras
+ val conversation = NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(n)
+ val last = conversation?.messages?.lastOrNull()
+ if (conversation != null && last != null) {
+ val sender = last.person?.name?.toString()
+ val group = conversation.isGroupConversation
+ val title = conversation.conversationTitle?.toString()?.takeIf { group } ?: sender
+ val text = last.text?.toString()?.let { if (group && sender != null) "$sender: $it" else it }
+ return Content(title, text, extras.text(Notification.EXTRA_SUB_TEXT)).takeIf { it.hasContent() }
+ }
+ val lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES)?.joinToString("\n")
+ val text = extras.text(Notification.EXTRA_BIG_TEXT) ?: lines?.ifBlank { null } ?: extras.text(Notification.EXTRA_TEXT)
+ val title = extras.text(Notification.EXTRA_TITLE_BIG) ?: extras.text(Notification.EXTRA_TITLE)
+ return Content(title, text, extras.text(Notification.EXTRA_SUB_TEXT)).takeIf { it.hasContent() }
+ }
+
+ private fun Content.hasContent() = !title.isNullOrBlank() || !text.isNullOrBlank()
+
+ private fun android.os.Bundle.text(key: String): String? = getCharSequence(key)?.toString()?.trim()?.ifEmpty { null }
+
+ /** Buttons, with their index as ID; reply actions take free text. */
+ private fun actions(n: Notification): List<MirroredAction> =
+ n.actions.orEmpty().mapIndexedNotNull { index, action ->
+ val title = action.title?.toString()?.trim()
+ if (title.isNullOrEmpty() || action.actionIntent == null) return@mapIndexedNotNull null
+ MirroredAction(
+ id = index.toString(),
+ title = title,
+ reply = action.remoteInputs.orEmpty().any { it.allowFreeFormInput },
+ )
+ }
+
+ private fun appName(pkg: String): String = names.get(pkg) ?: runCatching {
+ packages.getApplicationLabel(packages.getApplicationInfo(pkg, 0)).toString()
+ }.getOrDefault(pkg).also { names.put(pkg, it) }
+
+ /** The app's icon as a small PNG (the core sends it once per PC). */
+ private fun icon(pkg: String): ByteArray? = icons.get(pkg) ?: runCatching {
+ val bitmap = packages.getApplicationIcon(pkg).toBitmap(ICON_PX, ICON_PX, Bitmap.Config.ARGB_8888)
+ ByteArrayOutputStream().use { out ->
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
+ out.toByteArray()
+ }
+ }.getOrNull()?.takeIf { it.size <= MAX_ICON_BYTES }?.also { icons.put(pkg, it) }
+
+ private companion object {
+ const val ICON_PX = 96
+ const val MAX_ICON_BYTES = 64 * 1024
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 2e28d8b..f06129b 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -80,6 +80,12 @@ class MainActivity : ComponentActivity() {
}
}
+ override fun onResume() {
+ super.onResume()
+ // Back from Settings, maybe with notification access changed.
+ (application as NectarlinkApplication).core.refreshNotificationAccess()
+ }
+
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handlePairingLink(intent)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
index faaa590..d12b336 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
@@ -1,7 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package app.nectarlink.android.ui.settings
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
import android.os.Build
+import android.provider.Settings
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
@@ -14,6 +18,7 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
@@ -31,6 +36,7 @@ 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
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
@@ -40,6 +46,7 @@ import app.nectarlink.android.R
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.core.CoreStatus
import app.nectarlink.android.core.Device
+import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.android.ui.theme.Appearance
import app.nectarlink.android.ui.theme.LocalAppFonts
import app.nectarlink.android.ui.theme.Tokens
@@ -65,6 +72,10 @@ fun SettingsScreen(
modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),
)
+ Section(stringResource(R.string.settings_notifications)) {
+ NotificationAccess(state.notificationAccess)
+ }
+
Section(stringResource(R.string.settings_appearance)) {
Label(stringResource(R.string.settings_theme))
Choice(
@@ -163,6 +174,59 @@ fun SettingsScreen(
}
}
+/**
+ * Notification access, which mirroring needs. Android shows the switch in
+ * its own settings; sideloaded apps on Android 13+ must first be allowed
+ * "restricted settings" there.
+ */
+@Composable
+private fun NotificationAccess(granted: Boolean) {
+ val context = LocalContext.current
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Column(Modifier.weight(1f).padding(end = 12.dp)) {
+ Text(stringResource(R.string.notifications_title), style = MaterialTheme.typography.titleSmall)
+ Text(
+ stringResource(if (granted) R.string.notifications_on else R.string.notifications_off),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ val open = { context.startActivity(notificationAccessIntent(context)) }
+ if (granted) {
+ OutlinedButton(onClick = open) { Text(stringResource(R.string.action_manage)) }
+ } else {
+ Button(onClick = open) { Text(stringResource(R.string.action_allow)) }
+ }
+ }
+ if (!granted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Text(
+ stringResource(R.string.notifications_restricted),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.weight(1f),
+ )
+ TextButton(onClick = {
+ context.startActivity(
+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", context.packageName, null))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ )
+ }) { Text(stringResource(R.string.action_app_info)) }
+ }
+ }
+}
+
+/** Android's notification access screen, on Nectarlink's own switch where possible. */
+private fun notificationAccessIntent(context: Context): Intent =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS).putExtra(
+ Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME,
+ NotificationListener.component(context).flattenToString(),
+ )
+ } else {
+ Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
+ }.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
@Composable
private fun Section(title: String, content: @Composable () -> Unit) {
Text(
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 28f332a..7a950d8 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -50,6 +50,14 @@
<string name="settings_dynamic_color_hint">Use your wallpaper\'s colors.</string>
<string name="settings_devices">PCs</string>
<string name="settings_about">About</string>
+ <string name="settings_notifications">Notifications</string>
+ <string name="notifications_title">Show notifications on your PC</string>
+ <string name="notifications_on">On. Notifications appear on your paired PCs, where you can reply to and dismiss them.</string>
+ <string name="notifications_off">Nectarlink needs notification access to show this phone’s notifications on your PC.</string>
+ <string name="notifications_restricted">Switch greyed out? Open App info, tap ⋮, choose “Allow restricted settings”, then try again.</string>
+ <string name="action_allow">Allow</string>
+ <string name="action_manage">Manage</string>
+ <string name="action_app_info">App info</string>
<string name="theme_bloom">Bloom</string>
<string name="theme_graphite">Graphite</string>
<string name="mode_system">System</string>
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt
index 74e6492..d4f47c3 100644
--- a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt
+++ b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt
@@ -7,6 +7,7 @@ import app.nectarlink.core.DeviceKind
import app.nectarlink.core.DiscoveredDevice
import app.nectarlink.core.Event
import app.nectarlink.core.Link
+import app.nectarlink.core.Notification
import app.nectarlink.core.PairedDevice
import app.nectarlink.core.PairingFailure
import org.junit.Assert.assertEquals
@@ -72,4 +73,13 @@ class CoreStateTest {
state = state.reduce(Event.DiscoveryExpired("n"))
assertTrue(state.discovered.isEmpty())
}
-}
+
+ @Test
+ fun notificationEventsLeaveThePhoneStateAlone() {
+ val state = CoreState().reduce(Event.DeviceAdded(pc("a", "Desk", 10)))
+ val note = Notification("k", "com.chat", "Chat", "Sam", "Hi", null, 0L, emptyList(), false, null)
+ assertEquals(state, state.reduce(Event.NotificationPosted("a", note)))
+ assertEquals(state, state.reduce(Event.NotificationRemoved("a", "k")))
+ assertEquals(state, state.reduce(Event.NotificationsReset("a", listOf(note))))
+ assertTrue("access is off until the listener connects", !state.notificationAccess)
+ }}
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index dd851e2..1fe6ff9 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -111,6 +111,18 @@ enum Command {
},
/// Stay online and print events until Ctrl+C.
Run,
+ /// Dismiss a phone's notification (`run` prints the keys).
+ Dismiss { device: String, key: String },
+ /// Run an action of a phone's notification, or reply to it.
+ Act {
+ device: String,
+ key: String,
+ /// The action's ID (`run` prints them).
+ action: String,
+ /// Text to send, for a reply action.
+ #[arg(long)]
+ reply: Option<String>,
+ },
/// Show a notification on paired PCs as if this were a phone (use with
/// --as-phone), then stay online to show what the PC does with it.
Notify {
@@ -266,6 +278,20 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
node.ring(id, !off).await.context("ring failed")?;
println!("{}", if *off { "Stopped ringing." } else { "Ringing…" });
}
+ Command::Dismiss { device, key } => {
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ node.dismiss_notification(id, key.clone()).await.context("dismiss failed")?;
+ println!("Dismissed.");
+ }
+ Command::Act { device, key, action, reply } => {
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ node.run_notification_action(id, key.clone(), action.clone(), reply.clone())
+ .await
+ .context("action failed")?;
+ println!("Done.");
+ }
Command::Connect { device, addrs } => {
let id = resolve(node, device)?;
node.add_known_addrs(id, addrs);
@@ -454,12 +480,18 @@ fn print_event(node: &Node, event: &NodeEvent) {
NodeEvent::NotificationsReset { device, items } => {
println!("{}: {} notifications showing", name(device), items.len())
}
- NodeEvent::NotificationPosted { device, notification: n } => println!(
- "{}: {} · {}",
- name(device),
- n.app_name,
- n.title.as_deref().or(n.text.as_deref()).unwrap_or_default()
- ),
+ NodeEvent::NotificationPosted { device, notification: n } => {
+ println!(
+ "{}: {} · {} [key {}]",
+ name(device),
+ n.app_name,
+ n.title.as_deref().or(n.text.as_deref()).unwrap_or_default(),
+ n.key
+ );
+ for a in &n.actions {
+ println!(" action {}: {}{}", a.id, a.title, if a.reply { " (reply)" } else { "" });
+ }
+ }
NodeEvent::NotificationRemoved { device, .. } => {
println!("{}: a notification went away", name(device))
}
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index ab6b5f3..9a710b9 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -28,7 +28,7 @@ capability is missing.
| ID | Meaning | Unlocked by |
|---|---|---|
-| `notify.mirror` | Forwards notifications | notification access |
+| `notify.mirror` | Forwards notifications ([notifications service](notifications.md)) | notification access |
| `notify.reply` | Accepts inline replies and actions on notifications | notification access |
| `notify.sensitive` | Forwards notifications Android hides as sensitive (e.g. one-time codes) | Elevated |
| `sms.read` | Reads SMS conversations | SMS permission |