Media3 Cast Integration

android/skills/media/media3-cast-integration

作者 android42dc2270e960Complete terms in LICENSE.txt7.7K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫13 天前更新

Implements Google Cast support in Android apps using Jetpack Media3. Handles adding build dependencies, updating manifest, configuring OptionsProvider, and managing CastPlayer or RemoteCastPlayer for playback in both Compose and View-based UIs. Use when adding Cast functionality or migrating from legacy Cast SDK to Media3 Cast.

AI 產生的概覽

指導使用 Jetpack Media3 為 Android 應用程式加入 Google Cast 支援,涵蓋相依性、資訊清單、播放器與介面。

功能
此技能提供逐步說明,協助使用 Jetpack Media3 將 Google Cast 整合至 Android 應用程式。內容涵蓋宣告建置相依性、在資訊清單中設定 Cast 選項提供者、在 MediaSessionService 中實作 CastPlayer 或 RemoteCastPlayer、串接 Compose 或 View 式介面控制項,以及清除舊版 Cast SDK 程式碼。它也包含從舊版 Google Cast SDK 移轉的指引。
適用情境
適用於為 Android 應用程式加入 Cast 功能,或將現有應用程式從舊版 Google Cast SDK 移轉至 Jetpack Media3 Cast 的情境。它針對已具備 Media3 播放能力並希望支援投放至遠端裝置的應用程式。
執行需求
需要一個使用 Jetpack Media3 1.9.0 或更高版本的 Android 專案,並包含 Media3 ExoPlayer、session 與 UI 相依性;不隨附指令碼,僅提供指示與參考文件。

Prerequisites

  • Jetpack Media3 version must be >= 1.9.0. Cast isn't available in lower versions.

Glossary

  • CastPlayer : Media3 Player that controls playback on both local and remote Cast devices.
  • RemoteCastPlayer : Media3 Player that communicates with a Cast receiver, only used for remote playback.
  • Google Cast SDK: Legacy casting SDK in maintenance mode, superseded by Jetpack Media3.
  • OptionsProvider : Interface providing configuration options to initialize GMS CastContext.

Common guidelines

  • Legacy Google Cast SDK is in maintenance mode.
  • For new Cast setups:
    • You must use Jetpack Media3 Cast [blocked].
    • You mustn't use legacy Cast SDK unless explicitly requested.

Step 1: Set up dependencies

To complete this step, you MUST ensure the following:

  • In the app-level build file, declare the media3-cast dependency version 1.9.0 or higher.

    implementation("androidx.media3:media3-cast:1.11.1")
  • Ensure required Media3 dependencies are present:

    • androidx.media3:media3-exoplayer
    • androidx.media3:media3-session
    • androidx.media3:media3-ui-compose
  • If the application uses legacy Views, add media3-ui.

  • Enforce the same versions across all Media3 dependencies.

  • Use configurations in "Add build dependencies" section of Getting started with CastPlayer [blocked] as the source of truth.

  • For apps without an existing Cast integration:

    • Verify legacy Cast SDK (libs.play.services.cast.framework) is absent.
  • If Migrating from Legacy Cast SDK:

    • Add Media3 Cast dependencies first.
    • Keep existing legacy dependencies untouched at this stage to prevent compilation errors.

Step 2: Update the manifest

To complete this step, you MUST ensure the following:

  • Inside the manifest's <application> tag, declare the Cast options provider.
  • Use DefaultCastOptionsProvider by default. See the "OptionsProvider" section in Getting started with CastPlayer [blocked].
  • Declare a custom OptionsProvider only if explicitly requested. See Customize CastOptions [blocked].
  • Ensure INTERNET permission is present. Don't add any unnecessary permissions.
  • If Migrating from Legacy Cast SDK:
    • Don't delete existing custom options provider files or manifest entries.

Step 3: Implement the player and service

Architecture baseline

Before integrating Media3 Cast, an existing app follows one of two setups:

  • Local-only playback: Uses Media3 ExoPlayer only to support local playback.
  • Legacy Cast setup: Uses ExoPlayer for local playback, alongside a Player wrapper over the legacy RemoteMediaClient for remote playback. The UI interfaces with a MediaSession interacting with a ForwardingPlayer, which finally routes controls to either local or remote playback.

To complete this step, you MUST ensure the following:

  • Inside the application's MediaSessionService (or MediaLibraryService) onCreate() method, initialize ExoPlayer and CastPlayer.
  • Use CastPlayer by default unless RemoteCastPlayer is explicitly requested. See the "Build a CastPlayer" section in Getting started with CastPlayer [blocked].
  • For CastPlayer, pass the instance directly to MediaSession.Builder.
  • Replace all legacy forwarding player wrappers.
  • Don't delete legacy class files yet to prevent compilation errors during migration.

Advanced: RemoteCastPlayer

  • Use RemoteCastPlayer only if explicitly requested by user.

  • Initialize MediaSession with localPlayer and set a SessionAvailabilityListener on RemoteCastPlayer to transfer playback state on Cast session availability changes:

    class PlaybackService : MediaSessionService() { private var mediaSession: MediaSession? = null private lateinit var localPlayer: ExoPlayer private lateinit var remotePlayer: RemoteCastPlayer

    override fun onCreate() {  super.onCreate()
      localPlayer = ExoPlayer.Builder(this).build()  remotePlayer = RemoteCastPlayer.Builder(this).build()  mediaSession = MediaSession.Builder(this, localPlayer).build()
      remotePlayer.setSessionAvailabilityListener(    object : SessionAvailabilityListener {      override fun onCastSessionAvailable() {        transferPlaybackState(localPlayer, remotePlayer)      }
          override fun onCastSessionUnavailable() {        transferPlaybackState(remotePlayer, localPlayer)      }    }  )}
    private fun transferPlaybackState(previousPlayer: Player, newPlayer: Player) {  if (previousPlayer.mediaItemCount > 0) {    val transferStateBuilder = PlayerTransferState.builderFromPlayer(previousPlayer)    if (previousPlayer.playbackState == Player.STATE_ENDED ||        previousPlayer.currentPosition == C.TIME_END_OF_SOURCE) {      transferStateBuilder.setCurrentMediaItemIndex(0)      transferStateBuilder.setCurrentPosition(0)    }    transferStateBuilder.build().setToPlayer(newPlayer)  }
      previousPlayer.stop()  previousPlayer.clearMediaItems()  newPlayer.prepare()  mediaSession?.setPlayer(newPlayer)}

    }

Step 4: Set up the UI

Compose-based UI

To complete this step, you MUST ensure the following:

  • See the "Add a MediaRouteButton Composable to the Player" section in Getting started with CastPlayer [blocked] for Compose integration guidelines.

  • Use the MediaRouteButton composable from androidx.media3.cast package.

  • Don't use AndroidView in the Compose UI hierarchy.

  • Place MediaRouteButton in an area next to playback controls. Don't hide it behind system UI.

  • Don't use PlayerSurface for custom player UI. Use the Material3 Player composable.

  • Force recomposition on playback location shifts to ensure UI sync. Use key constraints on DeviceInfo changes:

    @OptIn(UnstableApi::class)@Composablefun MainScreen() {   val player = rememberMediaController()   val deviceInfo = rememberDeviceInfo(player)   player?.let { activePlayer -> key(deviceInfo) { PlayerScreen(player = activePlayer) } }}
    @Composableprivate fun rememberMediaController(): Player? {   // Logic to connect MediaController to MediaSession and release it}
    @Composableprivate fun rememberDeviceInfo(player: Player?): DeviceInfo? {   var deviceInfo by remember(player) { mutableStateOf(player?.deviceInfo) }   DisposableEffect(player) {       val activePlayer = player ?: return@DisposableEffect onDispose {}       deviceInfo = activePlayer.deviceInfo       val listener = object : Player.Listener {           override fun onDeviceInfoChanged(info: DeviceInfo) {               deviceInfo = info           }       }      activePlayer.addListener(listener)      onDispose { activePlayer.removeListener(listener) }   }   return deviceInfo}

View-based UI

To complete this step, you MUST ensure the following:

  • For View-based UI setups, see the "Add UI elements" section in Getting started with CastPlayer [blocked].

  • Casting Activities must extend AppCompatActivity or FragmentActivity and use a Theme.AppCompat descendant.

  • Ensure the AppCompat theme has a visible ActionBar if adding MediaRouteButton to the options menu.

  • Replace all instances and imports of CastButtonFactory with MediaRouteButtonFactory.

  • Rebind PlayerView.player references upon onDeviceInfoChanged events to prevent black screens or UI freezes:

    private val playerListener: Player.Listener =  object : Player.Listener {    override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) {      // Resetting to null bypasses PlayerView.setPlayer()'s instance equality check      // (this.player == player), forcing it to re-bind the video surface to the controller.      playerView.player = null      playerView.player = controller    }  }
  • Migration to Compose:

    • Don't use AndroidView to wrap the legacy PlayerView.
    • Implement Material3 Player composable and MediaRouteButton composable as per Getting started with CastPlayer [blocked].
    • Remove legacy XML layout declarations, menu files, and View component references.

Step 5: Clean up legacy Cast SDK code

[!WARNING] Warning: Don't perform cleanup directly. Remove legacy files and dependencies only when explicitly requested by the user.

To complete this step, you MUST ensure the following:

  • Remove legacy GMS Cast SDK (libs.play.services.cast.framework) and MediaRouter (libs.androidx.mediarouter) dependencies.
  • Delete custom OptionsProvider classes and manifest entries if DefaultCastOptionsProvider is adopted.
  • Remove legacy MediaTransferReceiver manifest declarations if present.
  • Remove all references to legacy Cast SDK components such as legacy helper wrappers, forwarding players, and RemoteMediaClient interfaces.
  • Delete legacy View XML layouts, menu files, and references to PlayerView if the migration to Compose is complete.

來源與署名

來源:android/skills位於media/media3-cast-integration提交42dc227

授權條款: Complete terms in LICENSE.txt

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 android/skills 的技能

Wear Compose M3

android

指導建置、更新與移轉 Wear OS Compose Material3 應用程式,並提供標準元件範例與版本規則。

Software Development7.7K13 天前更新

Display Glasses With Jetpack Compose Glimmer

android

Provides guidelines for developing projected Android XR apps for display glasses using the Jetpack Compose Glimmer UI toolkit. This skill covers foundational Glimmer design principles, workflows for implementing Jetpack Compose Glimmer, and interaction models for the glasses form factor. Use this skill to build an Android XR Augmented Experience app with Jetpack Compose Glimmer that adheres to the Glimmer design system for optimized glasses styling.

待分類7.7K13 天前更新

Play Billing Library Version Upgrade

android

引導將 Android 專案從舊版 Google Play 帳務程式庫升級到最新穩定版本。

Software Development7.7K13 天前更新

Leanback To Compose Tv Migration

android

Provides instructions and architectural patterns for migrating Android TV applications from legacy Leanback UI Toolkit, Android Views, or Support Fragments to Jetpack Compose for TV (androidx.tv). Use this skill for Leanback to Compose migrations, including browse screen, settings screen, authentication screen, login screen, or video playback screen migrations, or when replacing BrowseSupportFragment, LeanbackSettingsFragment, PreferenceFragment, BaseLeanbackPreferenceFragmentCompat, VideoSupportFragment, GuidedStepSupportFragment, SearchSupportFragment, VerticalGridSupportFragment, Presenter, ArrayObjectAdapter, or CursorMapper with modern Compose equivalents, implementing immersive carousels with focus memory, Media3 video playback with PlayerSurface, or custom 10-foot hero layouts.

待分類7.7K13 天前更新

Testing Setup

android

分析 Android 專案的測試設定,並安裝測試框架、測試基礎設施,以及單元、UI、截圖與端對端測試。

Software Development7.7K13 天前更新

Android Profiler

android

引導 Android 效能分析:錄製系統追蹤、堆積轉儲與方法記錄,並以 Perfetto SQL 進行分析。

Software Development7.7K13 天前更新