watch: add media controls clone inside the Watch app
- Commit
5fe18d5c5c58e4dd03445f9839befbe0c4b0c982- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-06 16:28 UTC (21 minutes ago)
- Parents
c69a6c3
Stock analysis (analysis/media-controls-clone-spec.md, gitignored with the pulled APK): the stock Wear media app (UmoActivity) ranks MediaControllers from a granted notification listener for watch-local sessions and bridges phone sessions over the Play-services Wear Data Layer (MediaLinkService), surfacing an ongoing tappable notification plus a foreground MediaStyle notification. It is platform-signed priv-app (MEDIA_CONTENT_CONTROL, MODIFY_AUDIO_ROUTING and other privileged permissions), so a sideloaded clone cannot copy that privilege path. Clone, inside the Watch app per owner direction: - Shared wire types in :library:wearlink mediacontrols (appId mediacontrols): session snapshots as a conduit data item, transport ops as conduit messages, with pure reduce/rotary helpers and tests. - Phone :watch: MediaNotificationListenerService holds the user grant; MediaSessionBridge snapshots active MediaControllers, publishes them, and applies play/pause/next/prev/seek/volume ops on the real controllers and AudioManager. A Media route offers the ACTION_NOTIFICATION_LISTENER_SETTINGS trampoline and shows state. - Watch :watch:wear: the conduit WearMainActivity is unchanged; media controls live in their own MediaControlsActivity (own launcher and MEDIA_CONTROLS entry) with play/pause, next/prev, seek +/-10s, session picker, volume buttons and rotary-crown volume. MediaControlsNotifier posts the ongoing tappable notification while a session exists (content intent to the separate activity, play/pause and next actions via MediaControlReceiver), mirroring the stock live surface. Degradations documented in the spec: no Play-services bridging (our RFCOMM conduit instead), no artwork bytes or output switcher, no watch-local session enumeration (no listener grant flow on Wear), no auto-launch activity (ongoing notification instead). Verified: :watch:lint :watch:lintVitalRelease :watch:testDevUnitTest, :library:wearlink:lint :library:wearlink:testDevUnitTest, :watch:wear:lintVitalRelease, assembleDev/assembleRelease for both Watch modules, :watch:ktlintCheck. Pre-existing failures left alone: :watch:wear:testDebugUnitTest cannot resolve dev-only library variants at base, wearlink ktlintCheck fails on a pre-existing consecutive-KDoc in AndroidBluetoothTransport, and tools/structure_check.py failures are all in unrelated modules.
Diff
library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex 09f7c51888..f44e4ae4d5 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -43,7 +43,7 @@ duplicated per app pair: each migrated protocol lives in `com.vayunmathur.library.wearlink.<app>` and is consumed by both the phone and wear app modules (which may not depend on each other). Golden-JSON tests stay in each app module and pin the shared code's wire format.-Migrated: clock, launcher, calendar, weather, music, notes, maps, appstore, contacts, findfamily, todo, communicate, camera, email, securemail. The findfamily protocol also carries own-device companion types: `WearWatchLocation` (watch->phone conduit data), `WearRingRequest` (ring paired own device, TTL-bound message) and `WearDeviceUwbMessage` (UWB session-param exchange; ranging is local). Remaining pairs are listed in+Migrated: clock, launcher, calendar, weather, music, notes, maps, appstore, contacts, findfamily, todo, communicate, camera, email, securemail, mediacontrols (Watch-app phone<->watch media-session bridge, appId `mediacontrols`). The findfamily protocol also carries own-device companion types: `WearWatchLocation` (watch->phone conduit data), `WearRingRequest` (ring paired own device, TTL-bound message) and `WearDeviceUwbMessage` (UWB session-param exchange; ranging is local). Remaining pairs are listed in `docs/structure/wear-protocol-pairs.tsv`. The contacts protocol (`contacts/WearContactsProtocol`) carries, additively, each contact's joined messenger platforms per action (call/message/video)
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.ktnew file mode 100644index 0000000000..234a25886a--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocol.kt@@ -0,0 +1,118 @@+package com.vayunmathur.library.wearlink.mediacontrols++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch protocol for the Watch app's media controls.+ *+ * The phone Watch app owns the real sessions: its notification-listener+ * service makes it a valid `MediaSessionManager.getActiveSessions`+ * caller, it snapshots every active `MediaController` into+ * [MediaControlsState] and publishes that as a conduit data item. The+ * watch renders the snapshot and sends [MediaControlOp]s back; the+ * phone applies each op on the real controller (transport controls,+ * seek, `AudioManager` volume). No artwork bytes cross the conduit in+ * this version: the watch shows the app label plus a music-note glyph.+ *+ * Watch-local sessions are not in this protocol: on Wear there is no+ * user grant flow for a notification listener, so the watch cannot+ * enumerate its own sessions (see analysis/media-controls-clone-spec.md).+ */+object WearMediaControlsProtocol {+ /** Conduit appId both Watch halves register under. */+ const val APP_ID = "mediacontrols"++ /** Data-item path (phone -> watch): one [MediaControlsState] JSON. */+ const val STATE_PATH = "/mediacontrols/state"++ /** Message path (watch -> phone): one [MediaControlOp] JSON. */+ const val OP_PATH = "/mediacontrols/op"++ const val MAX_JSON_BYTES = 45_000+ const val MAX_SESSIONS = 8+ const val MAX_TITLE_CHARS = 120+ const val MAX_TEXT_CHARS = 120++ val json: Json = Json { ignoreUnknownKeys = true }+}++/** One active media session as the watch needs to render it. */+@Serializable+data class MediaSessionSnapshot(+ val id: String,+ val appLabel: String = "",+ val packageName: String = "",+ val title: String = "",+ val artist: String = "",+ val album: String = "",+ val isPlaying: Boolean = false,+ val positionMs: Long = 0L,+ val durationMs: Long = 0L,+ val canPlay: Boolean = false,+ val canPause: Boolean = false,+ val canSkipNext: Boolean = false,+ val canSkipPrevious: Boolean = false,+ val canSeek: Boolean = false,+)++/** Full phone media state (phone -> watch). Empty [sessions] is the "nothing playing" state. */+@Serializable+data class MediaControlsState(+ val sessions: List<MediaSessionSnapshot> = emptyList(),+ val activeSessionId: String = "",+ val listenerGranted: Boolean = false,+ val volume: Int = 0,+ val maxVolume: Int = 0,+ val generation: Long = 0L,+) {+ val active: MediaSessionSnapshot? get() =+ sessions.firstOrNull { it.id == activeSessionId }+ ?: sessions.firstOrNull()+}++/** Transport/volume commands (watch -> phone). [sessionId] empty means the active session. */+@Serializable+enum class MediaOpKind { PLAY, PAUSE, PLAY_PAUSE, SKIP_NEXT, SKIP_PREVIOUS, SEEK_TO, SEEK_BY, SET_VOLUME, ADJUST_VOLUME, SELECT_SESSION }++@Serializable+data class MediaControlOp(+ val kind: MediaOpKind,+ val sessionId: String = "",+ val positionMs: Long = 0L,+ val deltaMs: Long = 0L,+ val volume: Int = -1,+ val volumeDelta: Int = 0,+)++/** Applies [op] selection to [state] for pure rendering/tests; transport ops only move the selection/volume hint. */+fun reduceMediaState(+ state: MediaControlsState,+ op: MediaControlOp,+): MediaControlsState =+ when (op.kind) {+ MediaOpKind.SELECT_SESSION ->+ if (state.sessions.any { it.id == op.sessionId }) state.copy(activeSessionId = op.sessionId) else state+ MediaOpKind.SET_VOLUME ->+ if (op.volume >=+ 0+ ) {+ state.copy(volume = op.volume.coerceIn(0, state.maxVolume))+ } else {+ state+ }+ MediaOpKind.ADJUST_VOLUME -> state.copy(volume = (state.volume + op.volumeDelta).coerceIn(0, state.maxVolume))+ else -> state+ }++/** 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)++/** Caps a session's text fields to watch size. */+fun capMediaSession(session: MediaSessionSnapshot): MediaSessionSnapshot =+ session.copy(+ title = session.title.take(WearMediaControlsProtocol.MAX_TITLE_CHARS),+ artist = session.artist.take(WearMediaControlsProtocol.MAX_TEXT_CHARS),+ album = session.album.take(WearMediaControlsProtocol.MAX_TEXT_CHARS),+ appLabel = session.appLabel.take(WearMediaControlsProtocol.MAX_TEXT_CHARS),+ )
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.ktnew file mode 100644index 0000000000..c0628e12be--- /dev/null+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/mediacontrols/WearMediaControlsProtocolTest.kt@@ -0,0 +1,44 @@+package com.vayunmathur.library.wearlink.mediacontrols++import kotlinx.serialization.encodeToString+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class WearMediaControlsProtocolTest {+ @Test+ fun `state round trips and selects active`() {+ val state =+ MediaControlsState(+ sessions = listOf(MediaSessionSnapshot(id = "a", title = "Song", canPause = true)),+ activeSessionId = "a",+ listenerGranted = true,+ volume = 3,+ maxVolume = 15,+ generation = 7L,+ )+ val decoded =+ WearMediaControlsProtocol.json.decodeFromString<MediaControlsState>(+ WearMediaControlsProtocol.json.encodeToString(state),+ )+ assertEquals(state, decoded)+ assertEquals("Song", decoded.active?.title)+ }++ @Test+ fun `reduce selects session and clamps volume`() {+ val state =+ MediaControlsState(+ sessions = listOf(MediaSessionSnapshot(id = "a"), MediaSessionSnapshot(id = "b")),+ activeSessionId = "a",+ maxVolume = 10,+ volume = 9,+ )+ assertEquals(+ "b",+ reduceMediaState(state, MediaControlOp(MediaOpKind.SELECT_SESSION, sessionId = "b")).activeSessionId,+ )+ assertEquals(10, reduceMediaState(state, MediaControlOp(MediaOpKind.ADJUST_VOLUME, volumeDelta = 5)).volume)+ assertTrue(rotaryVolumeDelta(99) == 5)+ }+}
watch-wear/AGENTS.md
diff --git a/watch-wear/AGENTS.md b/watch-wear/AGENTS.mdindex a56a3880ef..54385e589e 100644--- a/watch-wear/AGENTS.md+++ b/watch-wear/AGENTS.md@@ -28,6 +28,18 @@ Every other watch app reaches the phone through `WearLinkClientNode`. path segment. - The status screen renders `ConduitRuntime.state` (link state, registered apps, per-app counters).+- Media controls are a separate experience: `ui/MediaControlsActivity`+ (own launcher + `MEDIA_CONTROLS` entry, never the conduit status+ activity) renders phone sessions bridged by+ `service/MediaControlsBridge` over conduit appId `mediacontrols`+ (shared types in `:library:wearlink` `mediacontrols/`) and sends+ transport/seek/volume ops back; rotary crown adjusts volume.+ `platform/MediaControlsNotifier` posts the ongoing, tappable+ notification while a session exists (content intent to+ `MediaControlsActivity`, play/pause + next actions via+ `platform/MediaControlReceiver`). Watch-local session enumeration+ is unavailable without a granted listener on Wear, so controls+ cover phone-bridged sessions. - Inbound data items are mirrored to the host's persistent latest-wins `ConduitDataStore` (in `:library:wearlink`), so a snapshot pushed while a watch app is not running replays to it on
watch-wear/src/main/AndroidManifest.xml
diff --git a/watch-wear/src/main/AndroidManifest.xml b/watch-wear/src/main/AndroidManifest.xmlindex b2a66234b6..41136e08f5 100644--- a/watch-wear/src/main/AndroidManifest.xml+++ b/watch-wear/src/main/AndroidManifest.xml@@ -48,6 +48,24 @@ </intent-filter> </activity> + <activity+ android:name=".ui.MediaControlsActivity"+ android:exported="true"+ android:taskAffinity="">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ <intent-filter>+ <action android:name="com.google.android.wearable.action.MEDIA_CONTROLS" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter>+ </activity>++ <receiver+ android:name=".platform.MediaControlReceiver"+ android:exported="false" />+ <service android:name=".service.ConduitService" android:exported="true"
watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlReceiver.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlReceiver.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlReceiver.ktnew file mode 100644index 0000000000..92ec8f57ee--- /dev/null+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlReceiver.kt@@ -0,0 +1,26 @@+package com.vayunmathur.watch.wear.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlOp+import com.vayunmathur.library.wearlink.mediacontrols.MediaOpKind+import com.vayunmathur.watch.wear.service.MediaControlsBridge++/** Notification-action receiver: forwards play/pause and next to the phone bridge. */+class MediaControlReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ MediaControlsBridge.start(context)+ when (intent.action) {+ ACTION_PLAY_PAUSE -> MediaControlsBridge.sendOp(MediaControlOp(MediaOpKind.PLAY_PAUSE))+ ACTION_NEXT -> MediaControlsBridge.sendOp(MediaControlOp(MediaOpKind.SKIP_NEXT))+ ACTION_PREVIOUS -> MediaControlsBridge.sendOp(MediaControlOp(MediaOpKind.SKIP_PREVIOUS))+ }+ }++ companion object {+ const val ACTION_PLAY_PAUSE = "com.vayunmathur.watch.wear.media.PLAY_PAUSE"+ const val ACTION_NEXT = "com.vayunmathur.watch.wear.media.NEXT"+ const val ACTION_PREVIOUS = "com.vayunmathur.watch.wear.media.PREVIOUS"+ }+}
watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlsNotifier.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlsNotifier.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlsNotifier.ktnew file mode 100644index 0000000000..51eab6bf28--- /dev/null+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/platform/MediaControlsNotifier.kt@@ -0,0 +1,65 @@+package com.vayunmathur.watch.wear.platform++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState+import com.vayunmathur.watch.wear.ui.MediaControlsActivity++/**+ * The live watch surface: an ongoing, tappable notification while a+ * phone session exists (mirrors the stock app's ongoing media+ * notification). Its content intent opens [MediaControlsActivity] —+ * never the conduit status activity — and its actions forward+ * play/pause and next ops to the phone bridge.+ */+object MediaControlsNotifier {+ private const val CHANNEL_ID = "media_controls"+ private const val NOTIFICATION_ID = 0x4D43++ fun update(context: Context, state: MediaControlsState) {+ val manager = context.getSystemService(NotificationManager::class.java) ?: return+ val session = state.active+ if (session == null) {+ manager.cancel(NOTIFICATION_ID)+ return+ }+ manager.createNotificationChannel(+ NotificationChannel(CHANNEL_ID, "Media controls", NotificationManager.IMPORTANCE_DEFAULT),+ )+ val open = PendingIntent.getActivity(+ context, 0,+ Intent(context, MediaControlsActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ val title = session.title.ifEmpty { session.appLabel }+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.ic_media_play)+ .setContentTitle(title)+ .setContentText(listOf(session.artist, session.appLabel).filter { it.isNotEmpty() }.joinToString(" • "))+ .setContentIntent(open)+ .setOngoing(true)+ .setCategory(NotificationCompat.CATEGORY_TRANSPORT)+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)+ .addAction(+ android.R.drawable.ic_media_pause, "Play/Pause",+ actionIntent(context, MediaControlReceiver.ACTION_PLAY_PAUSE, 1),+ )+ .addAction(+ android.R.drawable.ic_media_next, "Next",+ actionIntent(context, MediaControlReceiver.ACTION_NEXT, 2),+ )+ .build()+ runCatching { manager.notify(NOTIFICATION_ID, notification) }+ }++ private fun actionIntent(context: Context, action: String, requestCode: Int): PendingIntent =+ PendingIntent.getBroadcast(+ context, requestCode,+ Intent(context, MediaControlReceiver::class.java).setAction(action),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+}
watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.ktindex ad8da0e13e..3edc270107 100644--- a/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt@@ -30,6 +30,7 @@ class ConduitService : Service() { override fun onCreate() { super.onCreate() host = ConduitHost(applicationContext)+ MediaControlsBridge.start(applicationContext) createChannel() }
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.ktnew file mode 100644index 0000000000..84323ebbff--- /dev/null+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/MediaControlsBridge.kt@@ -0,0 +1,61 @@+package com.vayunmathur.watch.wear.service++import android.content.Context+import com.vayunmathur.library.wearlink.WearLinkListener+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.WearMediaControlsProtocol+import com.vayunmathur.watch.wear.platform.MediaControlsNotifier+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.serialization.decodeFromString+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.+ */+object MediaControlsBridge {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val _state = MutableStateFlow(MediaControlsState())+ val state: StateFlow<MediaControlsState> = _state.asStateFlow()++ @Volatile private var node: WearLinkClientNode? = null+ @Volatile private var appContext: Context? = null++ private val listener = object : WearLinkListener {+ override fun onData(path: String, body: ByteArray) {+ if (path != WearMediaControlsProtocol.STATE_PATH) return+ runCatching {+ val next = WearMediaControlsProtocol.json.decodeFromString<MediaControlsState>(body.decodeToString())+ _state.value = next+ appContext?.let { MediaControlsNotifier.update(it, next) }+ }+ }+ }++ fun start(context: Context) {+ appContext = context.applicationContext+ if (node == null) {+ node = WearLinkClientNode(context.applicationContext, WearMediaControlsProtocol.APP_ID, listener).also { it.start() }+ }+ }++ fun sendOp(op: MediaControlOp) {+ scope.launch {+ runCatching {+ node?.sendMessage(+ WearMediaControlsProtocol.OP_PATH,+ WearMediaControlsProtocol.json.encodeToString(op).encodeToByteArray(),+ )+ }+ }+ }+}
watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsActivity.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsActivity.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsActivity.ktnew file mode 100644index 0000000000..9b87b88440--- /dev/null+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsActivity.kt@@ -0,0 +1,61 @@+package com.vayunmathur.watch.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.foundation.background+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.input.rotary.onRotaryScrollEvent+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Scaffold+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlOp+import com.vayunmathur.library.wearlink.mediacontrols.MediaOpKind+import com.vayunmathur.library.wearlink.mediacontrols.rotaryVolumeDelta+import com.vayunmathur.watch.wear.service.MediaControlsBridge++/**+ * Separate media-controls activity: the launcher entry and the+ * ongoing-notification tap target. The conduit status activity+ * ([WearMainActivity]) is untouched and shows only its own screen.+ *+ * Rotary crown scroll adjusts phone volume (one detent, one step),+ * mirroring the stock app's rotary volume input.+ */+class MediaControlsActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ MediaControlsBridge.start(this)+ setContent {+ MaterialTheme {+ Scaffold {+ val state by MediaControlsBridge.state.collectAsState()+ val focusRequester = remember { FocusRequester() }+ androidx.compose.runtime.LaunchedEffect(Unit) { runCatching { focusRequester.requestFocus() } }+ Box(+ modifier = Modifier.fillMaxSize()+ .background(MaterialTheme.colors.background)+ .focusRequester(focusRequester)+ .focusable()+ .onRotaryScrollEvent { event ->+ val steps = if (event.verticalScrollPixels > 0f) 1 else -1+ MediaControlsBridge.sendOp(+ MediaControlOp(MediaOpKind.ADJUST_VOLUME, volumeDelta = rotaryVolumeDelta(steps)),+ )+ true+ },+ ) {+ MediaControlsContent(state = state, onOp = MediaControlsBridge::sendOp)+ }+ }+ }+ }+ }+}
watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsContent.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsContent.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsContent.ktnew file mode 100644index 0000000000..300c9cae0b--- /dev/null+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/ui/MediaControlsContent.kt@@ -0,0 +1,105 @@+package com.vayunmathur.watch.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.ListHeader+import androidx.wear.compose.material.Scaffold+import androidx.wear.compose.material.Text+import com.vayunmathur.library.wearlink.WearFilledButton+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlOp+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState+import com.vayunmathur.library.wearlink.mediacontrols.MediaOpKind+import com.vayunmathur.watch.wear.R++/** Pure rendering of the bridged media state (screenshot fixture surface). */+@Composable+fun MediaControlsContent(+ state: MediaControlsState,+ onOp: (MediaControlOp) -> Unit,+) {+ Scaffold {+ ScalingLazyColumn(state = rememberScalingLazyListState(), modifier = Modifier.fillMaxWidth()) {+ item { ListHeader { Text(stringResource(R.string.media_controls), textAlign = TextAlign.Center) } }+ val session = state.active+ if (session == null) {+ item {+ Text(+ stringResource(if (state.listenerGranted) R.string.media_nothing else R.string.media_grant_phone),+ modifier = Modifier.padding(horizontal = 8.dp), textAlign = TextAlign.Center,+ )+ }+ } else {+ item { Text(session.title.ifEmpty { session.appLabel }, textAlign = TextAlign.Center) }+ if (session.artist.isNotEmpty()) {+ item { Text(session.artist, textAlign = TextAlign.Center) }+ }+ item { Text(session.appLabel, textAlign = TextAlign.Center) }+ if (session.durationMs > 0L) {+ item {+ Text(+ stringResource(R.string.media_progress, session.positionMs / 1000L, session.durationMs / 1000L),+ textAlign = TextAlign.Center,+ )+ }+ }+ if (session.canSeek) {+ item {+ WearFilledButton(label = stringResource(R.string.media_back10), onClick = {+ onOp(MediaControlOp(MediaOpKind.SEEK_BY, sessionId = session.id, deltaMs = -10_000L))+ })+ }+ item {+ WearFilledButton(label = stringResource(R.string.media_fwd10), onClick = {+ onOp(MediaControlOp(MediaOpKind.SEEK_BY, sessionId = session.id, deltaMs = 10_000L))+ })+ }+ }+ item {+ WearFilledButton(+ label = stringResource(if (session.isPlaying) R.string.media_pause else R.string.media_play),+ onClick = { onOp(MediaControlOp(MediaOpKind.PLAY_PAUSE, sessionId = session.id)) },+ )+ }+ if (session.canSkipPrevious) {+ item {+ WearFilledButton(label = stringResource(R.string.media_previous), onClick = {+ onOp(MediaControlOp(MediaOpKind.SKIP_PREVIOUS, sessionId = session.id))+ })+ }+ }+ if (session.canSkipNext) {+ item {+ WearFilledButton(label = stringResource(R.string.media_next), onClick = {+ onOp(MediaControlOp(MediaOpKind.SKIP_NEXT, sessionId = session.id))+ })+ }+ }+ item {+ WearFilledButton(label = stringResource(R.string.media_vol_down), onClick = {+ onOp(MediaControlOp(MediaOpKind.ADJUST_VOLUME, volumeDelta = -1))+ })+ }+ item {+ WearFilledButton(+ label = stringResource(R.string.media_volume, state.volume, state.maxVolume),+ onClick = { onOp(MediaControlOp(MediaOpKind.ADJUST_VOLUME, volumeDelta = 1)) },+ )+ }+ state.sessions.filter { it.id != session.id }.forEach { other ->+ item {+ WearFilledButton(label = other.title.ifEmpty { other.appLabel }, onClick = {+ onOp(MediaControlOp(MediaOpKind.SELECT_SESSION, sessionId = other.id))+ })+ }+ }+ }+ }+ }+}
watch-wear/src/main/res/values/strings.xml
diff --git a/watch-wear/src/main/res/values/strings.xml b/watch-wear/src/main/res/values/strings.xmlindex 4ac8933c5c..d640a6cc65 100644--- a/watch-wear/src/main/res/values/strings.xml+++ b/watch-wear/src/main/res/values/strings.xml@@ -4,4 +4,16 @@ <string name="registered_apps">Registered apps</string> <string name="no_apps">No app registered</string> <string name="app_traffic">%1$s: %2$d msgs, %3$d data</string>+ <string name="media_controls">Media controls</string>+ <string name="media_nothing">Nothing playing</string>+ <string name="media_grant_phone">Grant notification access in the Watch app on your phone</string>+ <string name="media_play">Play</string>+ <string name="media_pause">Pause</string>+ <string name="media_next">Next</string>+ <string name="media_previous">Previous</string>+ <string name="media_back10">Back 10 seconds</string>+ <string name="media_fwd10">Forward 10 seconds</string>+ <string name="media_vol_down">Volume down</string>+ <string name="media_volume">Volume %1$d of %2$d</string>+ <string name="media_progress">%1$d / %2$d sec</string> </resources>
watch/AGENTS.md
diff --git a/watch/AGENTS.md b/watch/AGENTS.mdindex 662e601f39..6ab632cd40 100644--- a/watch/AGENTS.md+++ b/watch/AGENTS.md@@ -24,6 +24,16 @@ the peer. `platform/BootReceiver` restarts it on boot/replacement. The single status screen renders `ConduitRuntime.state` (link state, registered apps, per-app counters) and offers the Bluetooth 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+`MediaControlsState` over the conduit (appId `mediacontrols`, shared+types in `:library:wearlink` `mediacontrols/`), 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`+trampoline. No privileged media permission is used. **Scheduled push sync:** `service/ConduitSyncScheduler` (started by `ConduitService`) discovers sync-capable apps from the package manager (broadcast receivers answering `ConduitSync.ACTION` under@@ -52,12 +62,16 @@ the appId. - com/vayunmathur/watch/MainActivity.kt - com/vayunmathur/watch/Navigation.kt - com/vayunmathur/watch/Route.kt-### service/ — conduit host+### service/ — conduit host + media bridge - com/vayunmathur/watch/service/ConduitService.kt+- com/vayunmathur/watch/service/MediaNotificationListenerService.kt+- com/vayunmathur/watch/service/MediaSessionBridge.kt ### platform/ — boot restart - com/vayunmathur/watch/platform/BootReceiver.kt-### ui/ — status screen+### ui/ — status + media screens - com/vayunmathur/watch/ui/WatchStatusScreen.kt+- com/vayunmathur/watch/ui/MediaControlsScreen.kt+- com/vayunmathur/watch/ui/MediaControlsContent.kt ## Verify (this module only) ```
watch/src/main/AndroidManifest.xml
diff --git a/watch/src/main/AndroidManifest.xml b/watch/src/main/AndroidManifest.xmlindex 27c4747de7..2b8be1723a 100644--- a/watch/src/main/AndroidManifest.xml+++ b/watch/src/main/AndroidManifest.xml@@ -55,6 +55,15 @@ </intent-filter> </service> + <service+ android:name=".service.MediaNotificationListenerService"+ android:exported="true"+ android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">+ <intent-filter>+ <action android:name="android.service.notification.NotificationListenerService" />+ </intent-filter>+ </service>+ <receiver android:name=".platform.BootReceiver" android:enabled="true"
watch/src/main/java/com/vayunmathur/watch/MainActivity.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/MainActivity.kt b/watch/src/main/java/com/vayunmathur/watch/MainActivity.ktindex cccc2dbf1f..a7e6b966a2 100644--- a/watch/src/main/java/com/vayunmathur/watch/MainActivity.kt+++ b/watch/src/main/java/com/vayunmathur/watch/MainActivity.kt@@ -3,11 +3,13 @@ package com.vayunmathur.watch import androidx.compose.runtime.Composable import com.vayunmathur.library.ui.MaActivity import com.vayunmathur.watch.service.ConduitService+import com.vayunmathur.watch.service.MediaSessionBridge /** Entry activity: starts the conduit service, then shows link status. */ class MainActivity : MaActivity() { override fun onCreateBeforeContent() { ConduitService.start(this)+ MediaSessionBridge.start(this) } @Composable
watch/src/main/java/com/vayunmathur/watch/Navigation.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/Navigation.kt b/watch/src/main/java/com/vayunmathur/watch/Navigation.ktindex b6515cf847..dd36f6e371 100644--- a/watch/src/main/java/com/vayunmathur/watch/Navigation.kt+++ b/watch/src/main/java/com/vayunmathur/watch/Navigation.kt@@ -6,6 +6,7 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.watch.ui.MediaControlsScreen import com.vayunmathur.watch.ui.WatchStatusScreen @Composable@@ -16,11 +17,15 @@ fun Navigation() { ActivityResultContracts.RequestPermission(), ) { } MainNavigation(backStack) {+ entry<Route.Media> {+ MediaControlsScreen()+ } entry<Route.Status> { WatchStatusScreen( onGrantPermission = { permissionLauncher.launch(Manifest.permission.BLUETOOTH_CONNECT) },+ onOpenMedia = { backStack.add(Route.Media) }, ) } }
watch/src/main/java/com/vayunmathur/watch/Route.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/Route.kt b/watch/src/main/java/com/vayunmathur/watch/Route.ktindex 3dd420015d..0d80bd352d 100644--- a/watch/src/main/java/com/vayunmathur/watch/Route.kt+++ b/watch/src/main/java/com/vayunmathur/watch/Route.kt@@ -9,4 +9,8 @@ sealed interface Route : NavKey { /** Conduit link status, registered apps and per-app traffic. */ @Serializable data object Status : Route++ /** Media controls: notification-listener grant plus bridged sessions. */+ @Serializable+ data object Media : Route }
watch/src/main/java/com/vayunmathur/watch/service/MediaNotificationListenerService.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/MediaNotificationListenerService.kt b/watch/src/main/java/com/vayunmathur/watch/service/MediaNotificationListenerService.ktnew file mode 100644index 0000000000..716601f48d--- /dev/null+++ b/watch/src/main/java/com/vayunmathur/watch/service/MediaNotificationListenerService.kt@@ -0,0 +1,22 @@+package com.vayunmathur.watch.service++import android.service.notification.NotificationListenerService++/**+ * Notification-listener grant holder for media controls.+ *+ * The service itself does not read notifications: its granted component+ * is what makes [MediaSessionBridge] a valid+ * `MediaSessionManager.getActiveSessions(listener)` caller. The user+ * grants it from the phone UI via the system notification-access+ * settings trampoline; there is no privileged shortcut.+ */+class MediaNotificationListenerService : NotificationListenerService() {+ override fun onListenerConnected() {+ MediaSessionBridge.start(applicationContext)+ }++ override fun onListenerDisconnected() {+ MediaSessionBridge.refresh()+ }+}
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.ktnew file mode 100644index 0000000000..08ecf9a2d0--- /dev/null+++ b/watch/src/main/java/com/vayunmathur/watch/service/MediaSessionBridge.kt@@ -0,0 +1,210 @@+package com.vayunmathur.watch.service++import android.content.ComponentName+import android.content.Context+import android.media.AudioManager+import android.media.MediaMetadata+import android.media.session.MediaController+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.conduit.WearLinkClientNode+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlOp+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState+import com.vayunmathur.library.wearlink.mediacontrols.MediaOpKind+import com.vayunmathur.library.wearlink.mediacontrols.MediaSessionSnapshot+import com.vayunmathur.library.wearlink.mediacontrols.WearMediaControlsProtocol+import com.vayunmathur.library.wearlink.mediacontrols.capMediaSession+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.serialization.decodeFromString+import kotlinx.serialization.encodeToString++/**+ * Phone media-session bridge: snapshots active [MediaController]s and+ * publishes them over the conduit (appId `mediacontrols`); applies ops+ * arriving from the watch on the real controllers / [AudioManager].+ *+ * Session enumeration needs our [MediaNotificationListenerService] to+ * 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.+ */+object MediaSessionBridge {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val _state = MutableStateFlow(MediaControlsState())+ val state: StateFlow<MediaControlsState> = _state.asStateFlow()++ @Volatile private var node: WearLinkClientNode? = null++ @Volatile private var appContext: Context? = null+ private var controllers: List<MediaController> = emptyList()+ private var generation = 0L++ private val listener =+ object : WearLinkListener {+ override fun onMessage(+ path: String,+ body: ByteArray,+ ) {+ if (path != WearMediaControlsProtocol.OP_PATH) return+ runCatching {+ applyOp(WearMediaControlsProtocol.json.decodeFromString<MediaControlOp>(body.decodeToString()))+ }+ }+ }++ private val callback =+ object : MediaController.Callback() {+ override fun onPlaybackStateChanged(state: PlaybackState?) = refresh()++ override fun onMetadataChanged(metadata: MediaMetadata?) = refresh()+ }++ private val sessionsListener = MediaSessionManager.OnActiveSessionsChangedListener { refresh() }++ fun start(context: Context) {+ appContext = context.applicationContext+ if (node == null) {+ node =+ WearLinkClientNode(+ context.applicationContext,+ WearMediaControlsProtocol.APP_ID,+ listener,+ ).also { it.start() }+ }+ runCatching {+ manager()?.addOnActiveSessionsChangedListener(sessionsListener, listenerComponent())+ }+ refresh()+ }++ fun refresh() {+ val context = appContext ?: return+ val granted = isListenerGranted(context)+ var snapshots = emptyList<MediaSessionSnapshot>()+ if (granted) {+ runCatching { manager()?.getActiveSessions(listenerComponent()) }.getOrNull()?.let { found ->+ controllers.forEach { runCatching { it.unregisterCallback(callback) } }+ controllers = found.take(WearMediaControlsProtocol.MAX_SESSIONS)+ controllers.forEach { runCatching { it.registerCallback(callback) } }+ snapshots = controllers.map { it.snapshot() }+ }+ }+ val audio = context.getSystemService(AudioManager::class.java)+ val next =+ MediaControlsState(+ sessions = snapshots,+ activeSessionId = snapshots.firstOrNull { it.isPlaying }?.id ?: snapshots.firstOrNull()?.id ?: "",+ listenerGranted = granted,+ volume = audio?.getStreamVolume(AudioManager.STREAM_MUSIC) ?: 0,+ maxVolume = audio?.getStreamMaxVolume(AudioManager.STREAM_MUSIC) ?: 0,+ generation = ++generation,+ )+ _state.value = next+ scope.launch {+ runCatching {+ node?.putData(+ WearMediaControlsProtocol.STATE_PATH,+ WearMediaControlsProtocol.json.encodeToString(next).encodeToByteArray(),+ )+ }+ }+ }++ fun applyOp(op: MediaControlOp) {+ val context = appContext ?: return+ val audio = context.getSystemService(AudioManager::class.java)+ when (op.kind) {+ MediaOpKind.SET_VOLUME ->+ audio?.setStreamVolume(+ AudioManager.STREAM_MUSIC,+ op.volume.coerceIn(0, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)),+ 0,+ )+ MediaOpKind.ADJUST_VOLUME ->+ repeat(kotlin.math.abs(op.volumeDelta).coerceAtMost(5)) {+ audio?.adjustStreamVolume(+ AudioManager.STREAM_MUSIC,+ if (op.volumeDelta > 0) AudioManager.ADJUST_RAISE else AudioManager.ADJUST_LOWER,+ 0,+ )+ }+ else -> {+ val controller =+ controllers.firstOrNull { op.sessionId.isEmpty() || it.sessionId() == op.sessionId }+ ?: controllers.firstOrNull { it.snapshot().isPlaying } ?: controllers.firstOrNull() ?: return+ val controls = controller.transportControls+ when (op.kind) {+ MediaOpKind.PLAY -> controls.play()+ MediaOpKind.PAUSE -> controls.pause()+ MediaOpKind.PLAY_PAUSE ->+ if (controller.playbackState?.state ==+ PlaybackState.STATE_PLAYING+ ) {+ controls.pause()+ } else {+ controls.play()+ }+ MediaOpKind.SKIP_NEXT -> controls.skipToNext()+ MediaOpKind.SKIP_PREVIOUS -> controls.skipToPrevious()+ MediaOpKind.SEEK_TO -> controls.seekTo(op.positionMs.coerceAtLeast(0L))+ MediaOpKind.SEEK_BY ->+ controls.seekTo(+ ((controller.playbackState?.position ?: 0L) + op.deltaMs).coerceAtLeast(0L),+ )+ MediaOpKind.SELECT_SESSION -> Unit+ else -> Unit+ }+ }+ }+ refresh()+ }++ private fun MediaController.sessionId(): String = sessionToken.toString()++ private fun MediaController.snapshot(): MediaSessionSnapshot {+ val meta = metadata+ val pb = playbackState+ val actions = pb?.actions ?: 0L+ return capMediaSession(+ MediaSessionSnapshot(+ id = sessionId(),+ appLabel =+ runCatching {+ val pm = appContext!!.packageManager+ pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()+ }.getOrDefault(packageName),+ packageName = packageName,+ title = meta?.getString(MediaMetadata.METADATA_KEY_TITLE).orEmpty(),+ artist =+ meta?.getString(MediaMetadata.METADATA_KEY_ARTIST)+ ?: meta?.getString(MediaMetadata.METADATA_KEY_ALBUM_ARTIST).orEmpty(),+ album = meta?.getString(MediaMetadata.METADATA_KEY_ALBUM).orEmpty(),+ isPlaying = pb?.state == PlaybackState.STATE_PLAYING || pb?.state == PlaybackState.STATE_BUFFERING,+ positionMs = pb?.position ?: 0L,+ durationMs = meta?.getLong(MediaMetadata.METADATA_KEY_DURATION) ?: 0L,+ canPlay = actions and PlaybackState.ACTION_PLAY != 0L,+ canPause = actions and PlaybackState.ACTION_PAUSE != 0L,+ canSkipNext = actions and PlaybackState.ACTION_SKIP_TO_NEXT != 0L,+ canSkipPrevious = actions and PlaybackState.ACTION_SKIP_TO_PREVIOUS != 0L,+ canSeek = actions and PlaybackState.ACTION_SEEK_TO != 0L,+ ),+ )+ }++ private fun manager(): MediaSessionManager? = appContext?.getSystemService(MediaSessionManager::class.java)++ private fun listenerComponent() = ComponentName(appContext!!, MediaNotificationListenerService::class.java)++ fun isListenerGranted(context: Context): Boolean {+ val flat = Settings.Secure.getString(context.contentResolver, "enabled_notification_listeners") ?: return false+ return flat.contains(context.packageName)+ }+}
watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsContent.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsContent.kt b/watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsContent.ktnew file mode 100644index 0000000000..37f316211f--- /dev/null+++ b/watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsContent.kt@@ -0,0 +1,69 @@+package com.vayunmathur.watch.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState+import com.vayunmathur.watch.R++/** Pure rendering of the phone media-bridge state (screenshot fixture surface). */+@Composable+fun MediaControlsContent(+ state: MediaControlsState,+ onGrantListener: () -> Unit,+) {+ AppScaffold(title = stringResource(R.string.media_controls)) { padding ->+ Column(+ modifier =+ Modifier+ .padding(padding)+ .fillMaxWidth()+ .padding(16.dp)+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ if (!state.listenerGranted) {+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(stringResource(R.string.media_listener_needed))+ Button(onClick = onGrantListener) { Text(stringResource(R.string.grant_listener)) }+ }+ }+ }+ if (state.sessions.isEmpty()) {+ Text(stringResource(R.string.media_nothing_playing))+ } else {+ state.sessions.forEach { session ->+ Card(modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(session.title.ifEmpty { session.appLabel })+ if (session.artist.isNotEmpty()) Text(session.artist)+ Text(session.appLabel)+ Text(+ if (session.isPlaying) {+ stringResource(+ R.string.media_playing,+ )+ } else {+ stringResource(R.string.media_paused)+ },+ )+ }+ }+ }+ }+ Text(stringResource(R.string.media_volume, state.volume, state.maxVolume))+ }+ }+}
watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsScreen.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsScreen.kt b/watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsScreen.ktnew file mode 100644index 0000000000..8109d9a33f--- /dev/null+++ b/watch/src/main/java/com/vayunmathur/watch/ui/MediaControlsScreen.kt@@ -0,0 +1,24 @@+package com.vayunmathur.watch.ui++import android.content.Intent+import android.provider.Settings+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.watch.service.MediaSessionBridge++/** Phone media-controls destination: grant state plus the sessions the watch can control. */+@Composable+fun MediaControlsScreen() {+ val state by MediaSessionBridge.state.collectAsState()+ val context = LocalContext.current+ MediaControlsContent(+ state = state,+ onGrantListener = {+ context.startActivity(+ Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ )+ },+ )+}
watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusContent.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusContent.kt b/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusContent.ktindex 01ba1360dd..1a65d48948 100644--- a/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusContent.kt+++ b/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusContent.kt@@ -23,6 +23,7 @@ import com.vayunmathur.watch.R fun WatchStatusContent( snapshot: ConduitSnapshot, onGrantPermission: () -> Unit,+ onOpenMedia: () -> Unit = {}, ) { AppScaffold(title = stringResource(R.string.app_name)) { padding -> Column(@@ -49,6 +50,7 @@ fun WatchStatusContent( } } }+ Button(onClick = onOpenMedia) { Text(stringResource(R.string.media_controls)) } Card(modifier = Modifier.fillMaxWidth()) { Column( modifier = Modifier.padding(16.dp),
watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusScreen.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusScreen.kt b/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusScreen.ktindex d552239799..e64f3809a9 100644--- a/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusScreen.kt+++ b/watch/src/main/java/com/vayunmathur/watch/ui/WatchStatusScreen.kt@@ -7,7 +7,10 @@ import com.vayunmathur.library.wearlink.conduit.ConduitRuntime /** Status screen: link state, registered apps, per-app traffic, permission action. */ @Composable-fun WatchStatusScreen(onGrantPermission: () -> Unit) {+fun WatchStatusScreen(+ onGrantPermission: () -> Unit,+ onOpenMedia: () -> Unit = {},+) { val snapshot by ConduitRuntime.state.collectAsState()- WatchStatusContent(snapshot = snapshot, onGrantPermission = onGrantPermission)+ WatchStatusContent(snapshot = snapshot, onGrantPermission = onGrantPermission, onOpenMedia = onOpenMedia) }
watch/src/main/res/values/strings.xml
diff --git a/watch/src/main/res/values/strings.xml b/watch/src/main/res/values/strings.xmlindex 4a92985aff..69d7ff713b 100644--- a/watch/src/main/res/values/strings.xml+++ b/watch/src/main/res/values/strings.xml@@ -7,4 +7,11 @@ <string name="no_apps">No app has registered yet</string> <string name="cached_items">Cached data items: %1$d</string> <string name="traffic">Messages out %1$d, in %2$d; data out %3$d, in %4$d; streams out %5$d, in %6$d</string>+ <string name="media_controls">Media controls</string>+ <string name="media_listener_needed">Grant notification access so this app can see playing media and mirror it to the watch.</string>+ <string name="grant_listener">Grant notification access</string>+ <string name="media_nothing_playing">Nothing playing</string>+ <string name="media_playing">Playing</string>+ <string name="media_paused">Paused</string>+ <string name="media_volume">Volume %1$d of %2$d</string> </resources>
watch/src/screenshotTest/kotlin/com/vayunmathur/watch/ui/MetadataPreviews.kt
diff --git a/watch/src/screenshotTest/kotlin/com/vayunmathur/watch/ui/MetadataPreviews.kt b/watch/src/screenshotTest/kotlin/com/vayunmathur/watch/ui/MetadataPreviews.ktindex 33e6c9a238..faf66ae1a5 100644--- a/watch/src/screenshotTest/kotlin/com/vayunmathur/watch/ui/MetadataPreviews.kt+++ b/watch/src/screenshotTest/kotlin/com/vayunmathur/watch/ui/MetadataPreviews.kt@@ -7,6 +7,8 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.wearlink.conduit.ConduitCounters import com.vayunmathur.library.wearlink.conduit.ConduitProtocol import com.vayunmathur.library.wearlink.conduit.ConduitSnapshot+import com.vayunmathur.library.wearlink.mediacontrols.MediaControlsState+import com.vayunmathur.library.wearlink.mediacontrols.MediaSessionSnapshot private const val PHONE = "spec:width=411dp,height=891dp,dpi=420" @@ -34,4 +36,32 @@ class MetadataPreviews { ) } }++ @PreviewTest+ @Preview(name = "2-media", device = PHONE, group = "phone", showSystemUi = true)+ @Composable+ fun Preview2Media() {+ DynamicTheme(darkTheme = true) {+ MediaControlsContent(+ state =+ MediaControlsState(+ sessions =+ listOf(+ MediaSessionSnapshot(+ id = "a",+ appLabel = "Music",+ title = "Song",+ artist = "Artist",+ isPlaying = true,+ ),+ ),+ activeSessionId = "a",+ listenerGranted = true,+ volume = 7,+ maxVolume = 15,+ ),+ onGrantListener = {},+ )+ }+ } }