skip to content

In Media3, how does a Player.Listener follow a lesson playlist through buffering, ready, ended and item changes, and how should it handle a PlaybackException?

level: middleimportance: must knowfreq 55%

answer

  1. four states plus an intention flag
  2. isPlaying needs three conditions
  3. transition reasons tell auto from seek
  4. error first, then STATE_IDLE
  5. errorCode groups, retry with prepare()

basics

~10 s

A Player.Listener gets onPlaybackStateChanged (IDLE, BUFFERING, READY, ENDED), onIsPlayingChanged and onMediaItemTransition with a reason. Errors arrive in onPlayerError as a PlaybackException with an errorCode, just before STATE_IDLE; recover by calling prepare() again.

solid answer

~40 s

I register a `Player.Listener` with `addListener`; its callbacks run on the player's application thread. `onPlaybackStateChanged` reports `STATE_IDLE`, `STATE_BUFFERING`, `STATE_READY` and `STATE_ENDED`, while `playWhenReady` is the separate intention to play, so I drive the play button from `onIsPlayingChanged`, which is true only when the player is ready, `playWhenReady` is true and nothing suppresses playback. For the lesson playlist, `onMediaItemTransition` gives the new item and a reason such as `MEDIA_ITEM_TRANSITION_REASON_AUTO` or `MEDIA_ITEM_TRANSITION_REASON_SEEK`, which I use to mark a lesson finished only on an automatic advance. `onPlayerError` delivers a `PlaybackException` just before the player drops to `STATE_IDLE`; I branch on `errorCode`, for example `ERROR_CODE_IO_NETWORK_CONNECTION_FAILED`, show a retry button and call `prepare()` again, since the playlist and position are kept.

code

kotlin · 34 lines
kotlin
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player

class LessonPlaybackListener(
    private val onLessonFinished: (String) -> Unit,
    private val showRetry: (String) -> Unit,
) : Player.Listener {
    private var currentLessonId: String? = null

    override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
        val previousLessonId = currentLessonId
        if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO && previousLessonId != null) {
            onLessonFinished(previousLessonId)
        }
        currentLessonId = mediaItem?.mediaId
    }

    override fun onPlaybackStateChanged(playbackState: Int) {
        if (playbackState == Player.STATE_ENDED) {
            currentLessonId?.let(onLessonFinished)
        }
    }

    override fun onPlayerError(error: PlaybackException) {
        when (error.errorCode) {
            PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
            PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT -> showRetry("You're offline")
            else -> showRetry("Playback failed: ${error.errorCodeName}")
        }
    }
}

// Retry button: player.prepare() resumes the same playlist at the same position.

go deeper

for a junior

Recall the four states and that playWhenReady is the user's intention, separate from the state.

for a middle

Explain the three conditions behind isPlaying, what each media item transition reason means, and why onPlayerError is followed by STATE_IDLE with the playlist kept.

for a senior

Show production error handling: branching on errorCode ranges, reading the cause chain for HTTP status, the behind-live-window recovery, and logging with getErrorCodeName.

for a principal

Decide what the team's playback analytics count as a start, a stall or a completion, and make every screen derive those from the same listener events.

## The four playback states Every Media3 `Player`, ExoPlayer included, reports its state through a registered **`Player.Listener`**. Its methods have empty defaults, so you override only what you need, and they are called on the thread returned by `getApplicationLooper()`. | State | Meaning | |---|---| | `STATE_IDLE` | Initial state, and the state after `stop()` or a failure; few resources are held. | | `STATE_BUFFERING` | The player cannot play from the current position yet, usually because more data must load. | | `STATE_READY` | The player can play immediately from the current position. | | `STATE_ENDED` | The player finished playing all media in the playlist. | `onPlaybackStateChanged(state)` reports each change. ## playWhenReady and isPlaying The state says what the player *can* do; **`playWhenReady`** says what the user *wants*. `play()` and `pause()` set it, and `onPlayWhenReadyChanged(playWhenReady, reason)` reports changes with a reason such as `PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST` or `PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY`. The player is actually **playing** only when all three hold: 1. the state is `STATE_READY`; 2. `playWhenReady` is `true`; 3. `getPlaybackSuppressionReason()` returns `PLAYBACK_SUPPRESSION_REASON_NONE`, so nothing such as a transient audio-focus loss is holding playback back. `isPlaying` combines the three, and `onIsPlayingChanged(isPlaying)` reports it. Drive a play/pause icon or a progress ticker from it, not from the state alone: a player in `STATE_BUFFERING` with `playWhenReady` true wants to play but is not playing. ## Following the lesson playlist A course unit is a playlist: `setMediaItems(lessons)` followed by `prepare()`. The playlist can be changed during playback with `addMediaItem`, `moveMediaItem`, `removeMediaItem` and `replaceMediaItem`, without preparing again. - **Navigation**: `seekToNextMediaItem()` and `hasNextMediaItem()`. The older `next()` and `hasNext()` were removed in 1.8.0. - **Transitions**: `onMediaItemTransition(mediaItem, reason)` fires whenever the current item changes. The reason is `MEDIA_ITEM_TRANSITION_REASON_AUTO` (the previous item finished), `MEDIA_ITEM_TRANSITION_REASON_SEEK` (the app or user jumped), `MEDIA_ITEM_TRANSITION_REASON_REPEAT` (the same item restarted) or `MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED` (the current item was removed, for example). - **The end**: with `REPEAT_MODE_OFF`, the player moves to `STATE_ENDED` after the last item; `clearMediaItems()` on a prepared player ends it too. Marking a lesson complete only on an `AUTO` transition, or on `STATE_ENDED` for the last one, keeps a skipped lesson from counting as watched. ## Errors: onPlayerError and PlaybackException A failure calls **`onPlayerError(error)`** immediately before the state moves to `STATE_IDLE`. The playlist and position survive, so calling `prepare()` again retries. `onPlayerErrorChanged` also reports when the error is cleared. - **`errorCode`** classifies the failure by range: 1xxx miscellaneous (`ERROR_CODE_BEHIND_LIVE_WINDOW`, `ERROR_CODE_TIMEOUT`), 2xxx input/output (`ERROR_CODE_IO_NETWORK_CONNECTION_FAILED`, `ERROR_CODE_IO_BAD_HTTP_STATUS`), 3xxx parsing, 4xxx decoding, 5xxx audio output and 6xxx DRM. - **`getErrorCodeName()`** gives a readable name for logs and crash reports. - **The cause chain** carries detail: an `HttpDataSource.InvalidResponseCodeException` in the causes exposes the `responseCode`. ExoPlayer passes an `ExoPlaybackException` subclass with fields such as `type` and `rendererIndex`. - **Live streams**: `ERROR_CODE_BEHIND_LIVE_WINDOW` means the position fell out of the live window; `seekToDefaultPosition()` then `prepare()` rejoins at the live edge. - **Stuck players**: since 1.9.0 ExoPlayer detects a player stuck buffering or playing without progress and fails it with `ERROR_CODE_TIMEOUT`, whose cause is a `StuckPlayerException`. A sensible lesson screen maps network codes to an offline banner with a retry button, decoding and parsing codes to a "this lesson can't play on your device" message, and logs everything with the code name. ## Listening with coroutines The `media3-common-ktx` module offers suspending alternatives to `addListener`, both marked `@UnstableApi`: - `Player.listen { events -> ... }` receives every batch of events. - `Player.listenTo(Player.EVENT_IS_PLAYING_CHANGED) { ... }`, added in 1.9.0, receives only the events you name. Both suspend until the coroutine is cancelled or the lambda throws, and they remove their listener on the way out, so launching them in a lifecycle-scoped coroutine replaces manual `removeListener` calls. They can be called from any thread, but the lambda always runs on the player's application thread, so it can call player methods safely. ## Individual callbacks or onEvents Each individual callback fires for one change. **`onEvents(player, events)`** fires afterwards with the set of events that happened together, which suits logic that reads several values at once, such as refreshing the whole control bar when either `EVENT_PLAYBACK_STATE_CHANGED` or `EVENT_PLAY_WHEN_READY_CHANGED` is present. Use individual callbacks when you need the reason a callback carries. Remove the listener with `removeListener` when its owner goes away, or the player keeps it, and whatever it references, alive.

  • When should lesson-screen logic use onEvents instead of an individual callback such as onMediaItemTransition?
    Individual callbacks fire one by one, so a getter read inside one can reflect a change whose own callback has not run yet. When logic needs several values together, such as the timeline and the current index, read them in `onEvents`, which runs after all individual callbacks for that batch. Keep individual callbacks when you need the reason they carry.
  • After onPlayerError, what is still in the player and how do you retry?
    The player is in `STATE_IDLE` but keeps its playlist, current item and position, and `playerError` holds the exception. Calling `prepare()` again reloads from that position; for `ERROR_CODE_BEHIND_LIVE_WINDOW` on a live stream, call `seekToDefaultPosition()` first so it rejoins at the live edge.
  • What does Media3 1.9.0's stuck-player detection change for your error handling?
    A player that stays buffering or playing without progress past the detection timeouts now fails with `ERROR_CODE_TIMEOUT`, its cause a `StuckPlayerException`, instead of spinning silently. Treat it like other failures: show a retry and log the code name, because the playlist and position are kept.

  • STATE_READY means the player is playing right now.
  • onPlayerError leaves the player in STATE_READY so it can continue.
  • A failed player must be released and rebuilt; prepare() cannot retry it.
  • Player.next() is the way to advance the playlist in current Media3.
  • Every onMediaItemTransition means the previous lesson finished.
  • Listener callbacks arrive on ExoPlayer's internal playback thread.

Assumes Media3 1.11; Player.next() and hasNext() were removed in 1.8.0, while stuck-player detection reporting ERROR_CODE_TIMEOUT and Player.listenTo arrived in 1.9.0.