cast-tv: auto-open app when a device connects in background
- Commit
a244d456f62d3ac138d15593dbfe8b808af454a0- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-19 18:54 UTC (1 month ago)
- Parents
90f75fe
Diff
cast/tv/src/main/AndroidManifest.xml
diff --git a/cast/tv/src/main/AndroidManifest.xml b/cast/tv/src/main/AndroidManifest.xmlindex 1744de855d..59c6b5e253 100644--- a/cast/tv/src/main/AndroidManifest.xml+++ b/cast/tv/src/main/AndroidManifest.xml@@ -9,6 +9,7 @@ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" /> <uses-feature android:name="android.software.leanback"
cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.ktindex 5fe6d81060..25ffd62d17 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/service/ReceiverService.kt@@ -33,6 +33,11 @@ private const val CHANNEL_ID = "cast_tv_receiver" private const val NOTIF_ID = 4301 +/** The high-importance channel whose full-screen intent opens the TV on its own. */+private const val INCOMING_CHANNEL_ID = "cast_tv_incoming"++private const val INCOMING_NOTIF_ID = 4302+ /** `Build.VERSION_CODES.UPSIDE_DOWN_CAKE`: `startForeground` takes a service type from API 34. */ private const val MIN_SERVICE_TYPE_SDK = 34 @@ -47,6 +52,12 @@ private const val MIN_SERVICE_TYPE_SDK = 34 * * `START_STICKY`, unlike `:cast`'s service: there is genuinely something to restore here. A restarted * receiver just re-advertises and waits, with no consent token or single-use permission involved.+ *+ * The service also opens the app itself when a phone connects while nothing is on screen. A direct+ * start is tried first and a full-screen intent is posted alongside it, the same pairing `clock`'s+ * `AlarmReceiver` uses: the direct start only survives when an exemption holds, and the intent is+ * what actually brings the TV forward from the background. Without either, a pairing code would sit+ * unseen in state until its socket timed out. */ class ReceiverService : Service() { @@ -64,6 +75,19 @@ class ReceiverService : Service() { importance = NotificationManager.IMPORTANCE_LOW, description = getString(R.string.tv_notification_channel_desc), )+ // Silent: appearing on screen is the alert, least of all in a living room. High importance+ // is what lets the full-screen intent below fire; the silence is what keeps it from ringing.+ ensureNotificationChannel(+ INCOMING_CHANNEL_ID,+ getString(R.string.tv_incoming_channel_name),+ importance = NotificationManager.IMPORTANCE_HIGH,+ description = getString(R.string.tv_incoming_channel_desc),+ configure = {+ setSound(null, null)+ enableVibration(false)+ lockscreenVisibility = Notification.VISIBILITY_PUBLIC+ },+ ) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {@@ -79,9 +103,19 @@ class ReceiverService : Service() { if (!collecting) { collecting = true scope.launch {+ var wasIncoming = false ReceiverController.state.collect { state -> getSystemService<NotificationManager>() ?.notify(NOTIF_ID, buildNotification(statusText(state.phase)))+ // The idle-to-active edge only: Pairing -> Connected -> Mirroring is one+ // arrival, not three, and refiring on each would stack intents for no reason.+ val incoming = state.phase.isIncoming+ if (incoming && !wasIncoming) bringToFront(statusText(state.phase))+ // Done once the picture is up - MainActivity moves on to MirrorActivity on its+ // own - or when the session ends. In between it stays as a tap-to-open backup+ // for a TV whose full-screen-intent access was never granted.+ if (!incoming || state.phase is ReceiverPhase.Mirroring) cancelIncoming()+ wasIncoming = incoming } } }@@ -135,11 +169,81 @@ class ReceiverService : Service() { private fun statusText(phase: ReceiverPhase): String = when (phase) { is ReceiverPhase.Pairing -> getString(R.string.tv_notification_text_pairing)+ is ReceiverPhase.Connected -> getString(R.string.tv_paired, phase.senderName) is ReceiverPhase.Mirroring -> getString(R.string.tv_mirroring, phase.sourceName) else -> getString(R.string.tv_ready_title) } + /**+ * Open the TV itself for an incoming phone, from the background.+ *+ * Always lands on `MainActivity` rather than going straight to the picture: an unknown phone+ * needs its pair code on screen first, and a known one passes through `Connected` so briefly+ * that aiming past it would show the mirror a frame before its surface exists. `MainActivity`+ * already moves on to `MirrorActivity` the moment frames arrive, so landing there covers both.+ *+ * `singleTop` + `clearTop` rather than a fresh task: when the idle screen is already up this+ * reuses it instead of stacking a second copy above the session it describes.+ */+ private fun bringToFront(text: String) {+ val open = Intent(this, MainActivity::class.java).apply {+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or+ Intent.FLAG_ACTIVITY_SINGLE_TOP or+ Intent.FLAG_ACTIVITY_CLEAR_TOP+ }+ // Best effort: allowed when an exemption holds, refused from the background otherwise.+ // The full-screen intent below is what covers that case, so a refusal is expected noise.+ runCatching { startActivity(open) }+ .onFailure { Log.status(TAG, "background activity start refused; relying on full-screen intent", it) }+ postIncoming(text, open)+ }++ /**+ * The notification that actually opens the TV from the background.+ *+ * A foreground service alone does not exempt a background activity start, so this is the+ * mechanism rather than the fallback. On Android 14+ it additionally needs the user to have+ * granted full-screen-intent access in Settings; without it the notification still lands in+ * the shade with a tap-to-open, and the miss is logged rather than retried.+ */+ private fun postIncoming(text: String, open: Intent) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&+ getSystemService<NotificationManager>()?.canUseFullScreenIntent() == false+ ) {+ Log.status(TAG, "USE_FULL_SCREEN_INTENT not granted; the TV may not open on its own")+ }+ val fullScreen = PendingIntent.getActivity(+ this,+ INCOMING_NOTIF_ID,+ open,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ val notification = NotificationCompat.Builder(this, INCOMING_CHANNEL_ID)+ .setSmallIcon(R.drawable.ic_cast_tv)+ .setContentTitle(getString(R.string.app_name))+ .setContentText(text)+ .setPriority(NotificationCompat.PRIORITY_HIGH)+ .setCategory(NotificationCompat.CATEGORY_CALL)+ .setFullScreenIntent(fullScreen, true)+ .setContentIntent(fullScreen)+ .setAutoCancel(true)+ .build()+ runCatching {+ getSystemService<NotificationManager>()?.notify(INCOMING_NOTIF_ID, notification)+ }.onFailure { Log.status(TAG, "could not post the incoming notification", it) }+ }++ private fun cancelIncoming() {+ runCatching { getSystemService<NotificationManager>()?.cancel(INCOMING_NOTIF_ID) }+ }++ /** A phone is arriving or here: pairing, paired, or streaming. Anything else is idle. */+ private val ReceiverPhase.isIncoming: Boolean+ get() = this is ReceiverPhase.Pairing ||+ this is ReceiverPhase.Connected ||+ this is ReceiverPhase.Mirroring+ private fun buildNotification(text: String): Notification { val open = PendingIntent.getActivity( this,
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.ktindex 7a27636641..1dd3dc81a8 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/ReceiverContent.kt@@ -6,18 +6,29 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+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.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text import com.vayunmathur.cast.tv.R import com.vayunmathur.cast.tv.platform.ReceiverFailure import com.vayunmathur.cast.tv.platform.ReceiverPhase import com.vayunmathur.cast.tv.platform.ReceiverUiState+import com.vayunmathur.library.ui.SpecialAccess+import androidx.tv.material3.Button /** * The idle and pairing screen.@@ -69,6 +80,7 @@ fun ReceiverContent(state: ReceiverUiState, modifier: Modifier = Modifier) { state.deviceName.ifBlank { stringResource(R.string.tv_name_unknown) }, ), )+ AutoOpenPrompt() } is ReceiverPhase.Pairing -> {@@ -146,3 +158,33 @@ private fun Detail(text: String, isError: Boolean = false) { }, ) }++/**+ * The one-tap grant for auto-open, shown on the idle screen until full-screen-intent access is+ * held.+ *+ * A `Button` rather than the phone-style permissions gate: the TV has two things to ask for+ * at most and a blocking wall would sit between a user and a screen whose whole job is one+ * sentence. Reprobed on every resume so a grant made in Settings clears this without reopening+ * the app.+ */+@Composable+private fun AutoOpenPrompt() {+ val context = LocalContext.current+ val lifecycleOwner = LocalLifecycleOwner.current+ var canAutoOpen by remember { mutableStateOf(SpecialAccess.hasFullScreenIntent(context)) }+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ if (event == Lifecycle.Event.ON_RESUME) {+ canAutoOpen = SpecialAccess.hasFullScreenIntent(context)+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }+ if (canAutoOpen) return+ Detail(stringResource(R.string.tv_auto_open_hint))+ Button(onClick = { SpecialAccess.requestFullScreenIntent(context) }) {+ Text(stringResource(R.string.tv_auto_open_grant))+ }+}
cast/tv/src/main/res/values/strings.xml
diff --git a/cast/tv/src/main/res/values/strings.xml b/cast/tv/src/main/res/values/strings.xmlindex f9174df172..184bd3c320 100644--- a/cast/tv/src/main/res/values/strings.xml+++ b/cast/tv/src/main/res/values/strings.xml@@ -40,4 +40,14 @@ <string name="tv_notification_channel_name">Receiving</string> <string name="tv_notification_channel_desc">Shown while this TV is available to cast to</string> <string name="tv_notification_text_pairing">Waiting for a pair code</string>++ <!-- Incoming connection: the high-importance channel whose full-screen intent opens the TV+ on its own when a phone connects while the app is in the background. Silent: appearing+ on screen is the alert. -->+ <string name="tv_incoming_channel_name">Incoming cast</string>+ <string name="tv_incoming_channel_desc">Used to open the TV automatically when a phone starts casting</string>++ <!-- Auto-open prompt on the idle screen, until full-screen-intent access is granted. -->+ <string name="tv_auto_open_hint">This TV can open itself when a phone starts casting. Allow it in Settings to turn that on.</string>+ <string name="tv_auto_open_grant">Allow auto-open</string> </resources>