Modern Apps git

← Modern-Apps.git

watch: start media bridge with conduit host, resend on connect

Commit
3c055c1fc83713dd274aa6edfb5246db3c6f586b
Author
Vayun Mathur <[email protected]>
When
2026-12-06 16:43 UTC (31 minutes ago)
Parents
d592702
Owner report: media controls not working after the Watch-app
clone (b1e0460b1/5fe18d5c5) was merged and installed.

Root causes, all on the conduit registration/publish seam:

- The phone MediaSessionBridge was only started from the
  transient MainActivity and from the notification listener
  connect callback. After install, reboot or process death the
  phone conduit host runs on its own (BootReceiver, other apps
  binding, the watch link) with no mediacontrols registration:
  ConduitHost drops sends from unregistered clients, so no
  snapshot was ever published and watch ops only queued. The
  watch half already started its bridge from its ConduitService;
  the phone ConduitService now does the same.

- The first publish raced the local Messenger bind and the
  RFCOMM connect and was lost, with no republish: the conduit
  host caches a data item locally but never resends its cache
  to the peer on connect. Both bridges now retry a failed
  WearLinkClientNode bind on every start instead of keeping a
  dead node forever, and the phone bridge republishes its
  snapshot on every conduit Connected transition, the pattern
  the clock/music publishers already use.

- Watch transport ops tapped before the client was bound or
  the link Connected were dropped (sendMessage result ignored),
  including the notification-action receiver cold start that
  starts the bridge and sends in one call. Ops now queue in a
  bounded pure MediaOpQueue (16, oldest dropped) in
  :library:wearlink and flush in order on (re)connect.

Paths and appId were already exact (mediacontrols,
/mediacontrols/state, /mediacontrols/op) and the phone listener
service manifest declaration is correct; both are now pinned
by router-level tests: registration records the caller package,
a registered phone bridge publishes the snapshot to the peer,
a registered watch bridge receives it on the exact path, an
op returns on the exact op path, a snapshot arriving while
unregistered replays on registration, and the op queue drains
bounded and in order.

No watch-wear manifest, label, icon or strings change, so this
merges cleanly with the concurrent icon work
(agent-mediacontrols-icon 476f58207), which owns the
MediaControlsActivity label/icon entries.

Verified with JAVA_HOME JDK21, ANDROID_HOME and the shared
GRADLE_USER_HOME, --max-workers=128:
./gradlew :watch:lint :watch:lintVitalRelease
:watch:testDevUnitTest :library:wearlink:lint
:library:wearlink:testDevUnitTest
:watch:wear:lintVitalRelease (BUILD SUCCESSFUL), plus
:watch:ktlintCheck, :library:wearlink:testDevUnitTest after
the final test edit and :watch:wear:assembleDev.
Pre-existing failures left alone and unchanged:
:watch:wear:testDebugUnitTest cannot resolve dev-only library
variants for a debug consumer, and :library:wearlink
ktlintCheck reports hundreds of violations in untouched
files; both are documented at the clone base and the touched
files add no new ktlint violations.

Diff

library/wearlink/src/main/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocol.ktindex 234a25886a..1ac8a45192 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocol.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocol.kt@@ -108,6 +108,41 @@ fun reduceMediaState( /** Rotary step -> volume delta: one detent is one volume step, clamped by the caller to the stream range. */ fun rotaryVolumeDelta(rotationSteps: Int): Int = rotationSteps.coerceIn(-5, 5) +/**+ * Bounded FIFO of watch transport ops that could not be sent yet+ * (conduit client not bound, or the peer link not Connected). The+ * watch bridge queues here instead of dropping the tap, and drains+ * it on every conduit (re)connect; the oldest op is dropped past+ * [MAX_PENDING_OPS] so a long disconnect cannot replay a stale burst.+ * Pure and synchronized, so the bridge may offer from any thread.+ */+class MediaOpQueue(+    private val maxPending: Int = MAX_PENDING_OPS,+) {+    private val pending = ArrayDeque<MediaControlOp>()++    @Synchronized+    fun offer(op: MediaControlOp) {+        pending.addLast(op)+        while (pending.size > maxPending) pending.removeFirst()+    }++    /** Remove and return every queued op in send order. */+    @Synchronized+    fun drain(): List<MediaControlOp> {+        val ops = pending.toList()+        pending.clear()+        return ops+    }++    @Synchronized+    fun size(): Int = pending.size++    companion object {+        const val MAX_PENDING_OPS = 16+    }+}+ /** Caps a session's text fields to watch size. */ fun capMediaSession(session: MediaSessionSnapshot): MediaSessionSnapshot =     session.copy(
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocolTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocolTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocolTest.ktindex c0628e12be..991006d670 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocolTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocolTest.kt@@ -1,8 +1,15 @@ package com.vayunmathur.library.wearlink.mediacontrols +import com.vayunmathur.library.wearlink.StreamHeader+import com.vayunmathur.library.wearlink.conduit.ConduitDownstream+import com.vayunmathur.library.wearlink.conduit.ConduitProtocol+import com.vayunmathur.library.wearlink.conduit.ConduitRouter+import com.vayunmathur.library.wearlink.conduit.ConduitUpstream+import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertTrue  class WearMediaControlsProtocolTest {@@ -41,4 +48,194 @@ class WearMediaControlsProtocolTest {         assertEquals(10, reduceMediaState(state, MediaControlOp(MediaOpKind.ADJUST_VOLUME, volumeDelta = 5)).volume)         assertTrue(rotaryVolumeDelta(99) == 5)     }++    @Test+    fun `appId is the route key of both exact paths`() {+        // The conduit routes by first path segment, so both Watch+        // halves must register this appId and publish/send on exactly+        // these paths or the host drops the traffic as unowned.+        assertEquals("mediacontrols", WearMediaControlsProtocol.APP_ID)+        assertEquals("/mediacontrols/state", WearMediaControlsProtocol.STATE_PATH)+        assertEquals("/mediacontrols/op", WearMediaControlsProtocol.OP_PATH)+        assertEquals(+            WearMediaControlsProtocol.APP_ID,+            ConduitProtocol.routeKey(WearMediaControlsProtocol.STATE_PATH),+        )+        assertEquals(WearMediaControlsProtocol.APP_ID, ConduitProtocol.routeKey(WearMediaControlsProtocol.OP_PATH))+        assertTrue(ConduitProtocol.owns(WearMediaControlsProtocol.APP_ID, WearMediaControlsProtocol.STATE_PATH))+        assertTrue(ConduitProtocol.owns(WearMediaControlsProtocol.APP_ID, WearMediaControlsProtocol.OP_PATH))+    }++    private class FakeDownstream : ConduitDownstream {+        val messages = mutableListOf<Pair<String, String>>()+        val data = mutableListOf<Pair<String, String>>()++        override fun deliverMessage(+            path: String,+            body: ByteArray,+        ): Boolean {+            messages.add(path to body.decodeToString())+            return true+        }++        override fun deliverData(+            path: String,+            body: ByteArray,+        ): Boolean {+            data.add(path to body.decodeToString())+            return true+        }++        override fun deliverStatus(+            state: String,+            peerLabel: String?,+            reason: String?,+        ): Boolean = true++        override fun deliverStreamOpen(+            streamId: Long,+            path: String,+            header: StreamHeader,+        ): Boolean = true++        override fun deliverStreamChunk(+            streamId: Long,+            body: ByteArray,+        ): Boolean = true++        override fun deliverStreamClose(+            streamId: Long,+            verified: Boolean,+        ): Boolean = true+    }++    private class FakeUpstream : ConduitUpstream {+        val messages = mutableListOf<Pair<String, String>>()+        val data = mutableListOf<Pair<String, String>>()++        override fun sendMessage(+            path: String,+            body: ByteArray,+            requireAck: Boolean,+        ): Boolean {+            messages.add(path to body.decodeToString())+            return true+        }++        override fun putData(+            path: String,+            body: ByteArray,+        ): Boolean {+            data.add(path to body.decodeToString())+            return true+        }++        override fun sendStream(+            path: String,+            header: StreamHeader,+            chunks: List<ByteArray>,+        ): Boolean = true+    }++    @Test+    fun `registered bridges exchange the snapshot and an op end to end`() {+        // Phone host: the phone bridge registers mediacontrols and+        // publishes the snapshot as local data under STATE_PATH.+        val phoneUpstream = FakeUpstream()+        val phoneRouter = ConduitRouter(upstream = phoneUpstream)+        val phoneClient = FakeDownstream()+        val state =+            MediaControlsState(+                sessions = listOf(MediaSessionSnapshot(id = "s1", title = "Song", isPlaying = true)),+                activeSessionId = "s1",+                listenerGranted = true,+                volume = 4,+                maxVolume = 15,+                generation = 3L,+            )+        val stateJson = WearMediaControlsProtocol.json.encodeToString(state)+        // Before registration the host has no mediacontrols client:+        // a peer op queues instead of being delivered (the failure+        // the phone ConduitService start fixes in production).+        assertFalse(phoneRouter.isRegistered(WearMediaControlsProtocol.APP_ID))+        phoneRouter.register(WearMediaControlsProtocol.APP_ID, phoneClient, "com.vayunmathur.watch")+        assertTrue(phoneRouter.isRegistered(WearMediaControlsProtocol.APP_ID))+        assertEquals(+            mapOf(WearMediaControlsProtocol.APP_ID to "com.vayunmathur.watch"),+            phoneRouter.registeredPackages(),+        )+        assertTrue(+            phoneRouter.onLocalData(+                WearMediaControlsProtocol.APP_ID,+                WearMediaControlsProtocol.STATE_PATH,+                stateJson.encodeToByteArray(),+            ),+        )+        assertEquals(listOf(WearMediaControlsProtocol.STATE_PATH to stateJson), phoneUpstream.data)++        // Watch host: the same snapshot arrives from the peer and is+        // delivered only to the registered mediacontrols client.+        val watchUpstream = FakeUpstream()+        val watchRouter = ConduitRouter(upstream = watchUpstream)+        val watchClient = FakeDownstream()+        val otherClient = FakeDownstream()+        watchRouter.register(WearMediaControlsProtocol.APP_ID, watchClient, "com.vayunmathur.watch")+        watchRouter.register("clock", otherClient, "com.vayunmathur.watch")+        watchRouter.onPeerData(WearMediaControlsProtocol.STATE_PATH, stateJson.encodeToByteArray())+        assertEquals(listOf(WearMediaControlsProtocol.STATE_PATH to stateJson), watchClient.data)+        assertTrue(otherClient.data.isEmpty())+        assertEquals(+            state,+            WearMediaControlsProtocol.json.decodeFromString<MediaControlsState>(watchClient.data.single().second),+        )++        // Back the other way: a watch op under OP_PATH reaches the+        // phone client registered for mediacontrols.+        val op = MediaControlOp(MediaOpKind.PLAY_PAUSE, sessionId = "s1")+        val opJson = WearMediaControlsProtocol.json.encodeToString(op)+        assertTrue(+            watchRouter.onLocalMessage(+                WearMediaControlsProtocol.APP_ID,+                WearMediaControlsProtocol.OP_PATH,+                opJson.encodeToByteArray(),+                false,+            ),+        )+        assertEquals(listOf(WearMediaControlsProtocol.OP_PATH to opJson), watchUpstream.messages)+        phoneRouter.onPeerMessage(WearMediaControlsProtocol.OP_PATH, opJson.encodeToByteArray())+        assertEquals(listOf(WearMediaControlsProtocol.OP_PATH to opJson), phoneClient.messages)+        assertEquals(+            op,+            WearMediaControlsProtocol.json.decodeFromString<MediaControlOp>(phoneClient.messages.single().second),+        )+    }++    @Test+    fun `snapshot published while the watch is unregistered replays on registration`() {+        val watchRouter = ConduitRouter(upstream = FakeUpstream())+        val stateJson =+            WearMediaControlsProtocol.json.encodeToString(+                MediaControlsState(listenerGranted = true, generation = 9L),+            )+        watchRouter.onPeerData(WearMediaControlsProtocol.STATE_PATH, stateJson.encodeToByteArray())+        val lateClient = FakeDownstream()+        watchRouter.register(WearMediaControlsProtocol.APP_ID, lateClient, "com.vayunmathur.watch")+        assertEquals(listOf(WearMediaControlsProtocol.STATE_PATH to stateJson), lateClient.data)+    }++    @Test+    fun `pending op queue drains in order and is bounded`() {+        val queue = MediaOpQueue(maxPending = 2)+        queue.offer(MediaControlOp(MediaOpKind.PLAY))+        queue.offer(MediaControlOp(MediaOpKind.PAUSE))+        queue.offer(MediaControlOp(MediaOpKind.SKIP_NEXT))+        assertEquals(2, queue.size())+        assertEquals(+            listOf(MediaOpKind.PAUSE, MediaOpKind.SKIP_NEXT),+            queue.drain().map { it.kind },+        )+        assertEquals(0, queue.size())+        assertTrue(queue.drain().isEmpty())+        assertEquals(16, MediaOpQueue.MAX_PENDING_OPS)+    } }
watch-wear/src/main/java/com/vayunmathur/watch/wear/service/MediaControlsBridge.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/MediaControlsBridge.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/MediaControlsBridge.ktindex 84323ebbff..7b82ea997b 100644--- a/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/MediaControlsBridge.kt+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/MediaControlsBridge.kt@@ -2,9 +2,11 @@ package com.vayunmathur.watch.wear.service  import android.content.Context import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkState import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode import com.vayunmathur.library.wearlink.mediacontrols.MediaControlOp import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState+import com.vayunmathur.library.wearlink.mediacontrols.MediaOpQueue import com.vayunmathur.library.wearlink.mediacontrols.WearMediaControlsProtocol import com.vayunmathur.watch.wear.platform.MediaControlsNotifier import kotlinx.coroutines.CoroutineScope@@ -21,13 +23,23 @@ import kotlinx.serialization.encodeToString  * Watch half of media controls: receives phone session snapshots over  * the conduit (appId `mediacontrols`), keeps the ongoing notification  * live, and sends transport ops back to the phone bridge.+ *+ * Ops tapped before the conduit client is bound or the peer link is+ * Connected are queued in [pendingOps] and flushed on (re)connect+ * instead of being dropped: the notification-action receiver starts+ * this bridge and sends in the same call, which is exactly that cold+ * race, and the activity sends as soon as it is tapped.  */ object MediaControlsBridge {     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)     private val _state = MutableStateFlow(MediaControlsState())     val state: StateFlow<MediaControlsState> = _state.asStateFlow() +    private val pendingOps = MediaOpQueue()+     @Volatile private var node: WearLinkClientNode? = null+    @Volatile private var observingLink = false+    @Volatile private var flushing = false     @Volatile private var appContext: Context? = null      private val listener = object : WearLinkListener {@@ -43,18 +55,75 @@ object MediaControlsBridge {      fun start(context: Context) {         appContext = context.applicationContext-        if (node == null) {-            node = WearLinkClientNode(context.applicationContext, WearMediaControlsProtocol.APP_ID, listener).also { it.start() }+        val client =+            synchronized(this) {+                node ?: WearLinkClientNode(context.applicationContext, WearMediaControlsProtocol.APP_ID, listener)+                    .also { node = it }+            }+        // No-op while bound, retries a failed first bind (see the+        // phone bridge): a dead node kept forever never registers+        // mediacontrols, so snapshots are never delivered to it.+        client.start()+        observeLink(client)+    }++    private fun observeLink(client: WearLinkClientNode) {+        synchronized(this) {+            if (observingLink) return+            observingLink = true+        }+        scope.launch {+            var wasConnected = false+            client.state.collect { linkState ->+                val connected = linkState is WearLinkState.Connected+                if (connected && !wasConnected) flushPending()+                wasConnected = connected+            }         }     }      fun sendOp(op: MediaControlOp) {+        // Queue first, then drain: a tap that arrives before the client+        // is bound or the link is Connected stays in order behind any+        // op already waiting instead of being dropped or overtaking it.+        pendingOps.offer(op)+        flushPending()+    }++    /** Send every queued op in order; ops that fail again stay queued for the next connect. */+    private fun flushPending() {+        synchronized(this) {+            if (flushing) return+            flushing = true+        }         scope.launch {-            runCatching {-                node?.sendMessage(-                    WearMediaControlsProtocol.OP_PATH,-                    WearMediaControlsProtocol.json.encodeToString(op).encodeToByteArray(),-                )+            try {+                val client = node ?: return@launch+                if (!client.isConnected) return@launch+                while (true) {+                    val ops = pendingOps.drain()+                    if (ops.isEmpty()) break+                    var failedAt = -1+                    for ((index, op) in ops.withIndex()) {+                        val sent =+                            runCatching {+                                client.sendMessage(+                                    WearMediaControlsProtocol.OP_PATH,+                                    WearMediaControlsProtocol.json.encodeToString(op).encodeToByteArray(),+                                )+                            }.getOrDefault(false)+                        if (!sent) {+                            failedAt = index+                            break+                        }+                    }+                    if (failedAt >= 0) {+                        ops.drop(failedAt).forEach { pendingOps.offer(it) }+                        break+                    }+                }+            } finally {+                synchronized(this@MediaControlsBridge) { flushing = false }             }         }     }
watch/AGENTS.md
diff --git a/watch/AGENTS.md b/watch/AGENTS.mdindex 6ab632cd40..8108897c68 100644--- a/watch/AGENTS.md+++ b/watch/AGENTS.md@@ -27,9 +27,13 @@ permission grant. **Media controls (phone half):** `service/MediaNotificationListenerService` holds the user-granted notification-listener component that makes `service/MediaSessionBridge` a valid `MediaSessionManager.getActiveSessions`-caller. The bridge snapshots active `MediaController`s, publishes+caller. `service/ConduitService` starts the bridge with the conduit+host (as the watch half does), so `mediacontrols` is registered+whenever the host runs, not only while `MainActivity` or the listener+is alive. The bridge snapshots active `MediaController`s, publishes `MediaControlsState` over the conduit (appId `mediacontrols`, shared-types in `:library:wearlink` `mediacontrols/`), and applies watch+types in `:library:wearlink` `mediacontrols/`), republishes on every+conduit connect, and applies watch transport/seek/volume ops on the real controllers and `AudioManager`. The `Media` route (`ui/MediaControlsScreen`) shows grant state and sessions and offers the `ACTION_NOTIFICATION_LISTENER_SETTINGS`
watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.ktindex f102bf13c7..7ab5e807b4 100644--- a/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt@@ -34,6 +34,15 @@ class ConduitService : Service() {     override fun onCreate() {         super.onCreate()         host = ConduitHost(applicationContext)+        // The media bridge is a conduit client of this host (appId+        // mediacontrols). Start it with the host, not only from the+        // transient MainActivity or the notification listener: after+        // install, reboot or process death the host runs (boot, other+        // apps binding, the watch link) while neither of those has run,+        // and an unregistered bridge can neither publish its snapshot+        // (the host drops sends from unregistered clients) nor receive+        // watch ops. The watch half starts its bridge the same way.+        MediaSessionBridge.start(applicationContext)         syncScheduler = ConduitSyncScheduler(applicationContext, scope)         createChannel()     }
watch/src/main/java/com/vayunmathur/watch/service/MediaSessionBridge.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/MediaSessionBridge.kt b/watch/src/main/java/com/vayunmathur/watch/service/MediaSessionBridge.ktindex 08ecf9a2d0..f971d6771a 100644--- a/watch/src/main/java/com/vayunmathur/watch/service/MediaSessionBridge.kt+++ b/watch/src/main/java/com/vayunmathur/watch/service/MediaSessionBridge.kt@@ -9,6 +9,7 @@ import android.media.session.MediaSessionManager import android.media.session.PlaybackState import android.provider.Settings import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkState import com.vayunmathur.library.wearlink.conduit.WearLinkClientNode import com.vayunmathur.library.wearlink.mediacontrols.MediaControlOp import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState@@ -35,6 +36,10 @@ import kotlinx.serialization.encodeToString  * be user-granted: without the grant `getActiveSessions` throws, the  * state publishes `listenerGranted = false` and the UI offers the  * system grant trampoline. No privileged permission is used.+ *+ * Started by the phone `ConduitService` (the conduit host this bridge+ * is a client of), by `MainActivity` and by the listener's connect+ * callback, and republishes its snapshot on every conduit connect.  */ object MediaSessionBridge {     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -43,6 +48,8 @@ object MediaSessionBridge {      @Volatile private var node: WearLinkClientNode? = null +    @Volatile private var observingLink = false+     @Volatile private var appContext: Context? = null     private var controllers: List<MediaController> = emptyList()     private var generation = 0L@@ -71,20 +78,53 @@ object MediaSessionBridge {      fun start(context: Context) {         appContext = context.applicationContext-        if (node == null) {-            node =-                WearLinkClientNode(+        val client =+            synchronized(this) {+                node ?: WearLinkClientNode(                     context.applicationContext,                     WearMediaControlsProtocol.APP_ID,                     listener,-                ).also { it.start() }-        }+                ).also { node = it }+            }+        // WearLinkClientNode.start() is a no-op while bound and retries+        // a bind that failed (Watch app absent, service unavailable), so+        // every bridge start re-offers it: keeping a dead first-attempt+        // node forever left mediacontrols unregistered until process+        // death, and the conduit host drops sends from unregistered+        // clients.+        client.start()+        observeLink(client)         runCatching {             manager()?.addOnActiveSessionsChangedListener(sessionsListener, listenerComponent())         }         refresh()     } +    /**+     * Republish on every conduit (re)connect. The first publish from+     * [start] races both the local Messenger bind (no conduit yet, the+     * send is refused) and the RFCOMM link (the host caches the item+     * locally but does not resend its cache to the peer on connect), so+     * without this the watch kept the empty default state — no sessions,+     * grant prompt forever — until a media session happened to change.+     * Every other conduit publisher republishes on Connected the same+     * way.+     */+    private fun observeLink(client: WearLinkClientNode) {+        synchronized(this) {+            if (observingLink) return+            observingLink = true+        }+        scope.launch {+            var wasConnected = false+            client.state.collect { linkState ->+                val connected = linkState is WearLinkState.Connected+                if (connected && !wasConnected) refresh()+                wasConnected = connected+            }+        }+    }+     fun refresh() {         val context = appContext ?: return         val granted = isListenerGranted(context)