---
name: media3-cast-integration
description: 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.
license: Complete terms in LICENSE.txt
metadata:
  author: Google LLC
  last-updated: '2026-11-18'
  keywords:
    - Android
    - Media3
    - Cast
    - Integration
    - Migration
    - ExoPlayer
    - MediaSession
    - Jetpack Media3
title: media3-cast-integration
canonical_url: https://skilld.dev/gh/android/skills/media3-cast-integration
last_updated: 2026-11-24T09:07:15.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/android/media/media3/cast/create-castplayer.md](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md), [references/android/media/media3/cast/customize-castoptions.md](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/customize-castoptions.md), [references/android/media/media3/cast/index.md](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/index.md).
>
> If the user asked to install this Skill, run `npx skilld install android/skills/media3-cast-integration`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/media3-cast-integration`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/android/skills/media3-cast-integration) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/media3-cast-integration`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/media3-cast-integration --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/media3-cast-integration --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

## 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](https://developers.google.com/cast) is in maintenance mode.
- For new Cast setups:
  - You must use [Jetpack Media3 Cast](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/index.md).
  - 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.

  ```kotlin
  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`
  - `androidx.media3:media3-ui-compose-material3`
- 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](references/android/media/media3/cast/create-castplayer.md) 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](references/android/media/media3/cast/create-castplayer.md).
- Declare a custom `OptionsProvider` only if explicitly requested. See [Customize CastOptions](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/customize-castoptions.md).
- 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](references/android/media/media3/cast/create-castplayer.md).
- 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:

```kotlin
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](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md) for Compose integration guidelines.
- Use the [`MediaRouteButton` composable](https://developer.android.com/reference/kotlin/androidx/media3/cast/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](https://developer.android.com/reference/kotlin/androidx/media3/ui/compose/material3/Player.composable).
- Force recomposition on playback location shifts to ensure UI sync. Use key
  constraints on `DeviceInfo` changes:

  ```kotlin
  @OptIn(UnstableApi::class)
  @Composable
  fun MainScreen() {
     val player = rememberMediaController()
     val deviceInfo = rememberDeviceInfo(player)
     player?.let { activePlayer -> key(deviceInfo) { PlayerScreen(player = activePlayer) } }
  }

  @Composable
  private fun rememberMediaController(): Player? {
     // Logic to connect MediaController to MediaSession and release it
  }

  @Composable
  private 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](references/android/media/media3/cast/create-castplayer.md).
- 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:

  ```kotlin
  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](https://developer.android.com/reference/kotlin/androidx/media3/ui/compose/material3/Player.composable) and [`MediaRouteButton` composable](https://developer.android.com/reference/kotlin/androidx/media3/cast/MediaRouteButton.composable) as per [Getting started with CastPlayer](https://skilld.dev/api/skills-raw/android/skills/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md).
  - 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.
