skip to content

In Media3, how do MediaSession and MediaSessionService keep a lesson's audio playing with the screen off and give the learner system playback controls?

level: middleimportance: must knowfreq 60%

answer

  1. the player moves out of the activity
  2. a service subclass that returns the session
  3. manifest type, permissions, intent filter
  4. UI talks through a controller
  5. foreground while playing, notification for free

basics

~20 s

Move the ExoPlayer into a MediaSessionService subclass, wrap it in a MediaSession returned from onGetSession, and declare the service with foregroundServiceType mediaPlayback. Media3 runs it in the foreground with a media notification while playing; screens control it through a MediaController.

solid answer

~40 s

An activity-owned player stops when the activity does, so I move playback into a `MediaSessionService` subclass. In `onCreate` I build the `ExoPlayer` and `MediaSession.Builder(this, player).build()`; `onGetSession` returns that session, and `onDestroy` releases the player and then the session. The manifest declares the service with `android:foregroundServiceType="mediaPlayback"`, `exported="true"` and the `androidx.media3.session.MediaSessionService` intent filter, plus the `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_MEDIA_PLAYBACK` permissions. When playback starts, Media3 promotes the service to the foreground and posts a media-style notification built from the session, which also feeds the lock screen, Bluetooth buttons and other controllers. The activity connects with a `SessionToken` and `MediaController.Builder(...).buildAsync()`; the controller implements `Player`, so `PlayerView` can show it. I also build the player with `setAudioAttributes(..., true)` so it handles audio focus.

code

kotlin · 34 lines
kotlin
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService

class PlaybackService : MediaSessionService() {
    private var mediaSession: MediaSession? = null

    override fun onCreate() {
        super.onCreate()
        val audioAttributes = AudioAttributes.Builder()
            .setUsage(C.USAGE_MEDIA)
            .setContentType(C.AUDIO_CONTENT_TYPE_SPEECH)
            .build()
        val player = ExoPlayer.Builder(this)
            .setAudioAttributes(audioAttributes, /* handleAudioFocus= */ true)
            .setHandleAudioBecomingNoisy(true)
            .build()
        mediaSession = MediaSession.Builder(this, player).build()
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
        mediaSession

    override fun onDestroy() {
        mediaSession?.run {
            player.release()
            release()
            mediaSession = null
        }
        super.onDestroy()
    }
}

go deeper

for a junior

Recall that background playback needs a MediaSession inside a MediaSessionService, and name the manifest's mediaPlayback type.

for a middle

Explain the service lifecycle methods, how the UI reaches the player through a MediaController, and when Media3 promotes the service to the foreground.

for a senior

Diagnose why audio stops on lock or the service never stops: missing type or permission, unreleased controllers, a second session, and opting into audio focus.

for a principal

Set the team rule for which playback must survive the screen turning off, and make the service the single owner of that player and its release.

## Why the activity cannot own the player In the language-learning app, a learner starts a lesson, locks the phone and keeps listening to the narration. If the `ExoPlayer` lives in the activity, it is released in `onStop`, and even a player that is never released runs in a process Android may freeze or kill once nothing in it is in the foreground. Lock-screen controls, headset buttons and other apps also need a published **media session** to find and control the playback. Media3 solves both with two classes: - **`MediaSession`** wraps any `Player` and publishes its state and commands to the system and to other apps. There are no connectors: the session takes the player directly. - **`MediaSessionService`** is a bound service that hosts sessions. It becomes a **foreground service** while playback is ongoing, so the process keeps running with the screen off, and it posts the media notification for you. ## The service 1. **`onCreate`**: build the `ExoPlayer` and `MediaSession.Builder(this, player).build()`. Build the player with `setAudioAttributes(attributes, true)` so it requests and handles audio focus, which is off by default, and with `setHandleAudioBecomingNoisy(true)` so unplugging headphones pauses it. 2. **`onGetSession(controllerInfo)`**: return the session. Returning `null` rejects that controller. 3. **`onDestroy`**: release the player, then the session, then call `super.onDestroy()`. 4. **`onTaskRemoved`** (optional): since 1.4.0 the default keeps the service running if a session is playing when the learner swipes the app away and otherwise calls `pauseAllPlayersAndStopSelf()`. Override it to always stop, for example. A second session with the same ID throws `IllegalStateException` ("Session ID must be unique"), which typically means an earlier session was never released. ## The manifest - `<service android:name=".PlaybackService" android:foregroundServiceType="mediaPlayback" android:exported="true">` with an `<intent-filter>` containing the action `androidx.media3.session.MediaSessionService`. Adding `android.media.browse.MediaBrowserService` lets older media-browser clients connect too. - `<uses-permission>` entries for `android.permission.FOREGROUND_SERVICE` and `android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK`; the Android foreground-service rules behind these belong to the platform, and Media3 only asks you to declare them. ## Connecting the UI The activity no longer builds a player. It creates `SessionToken(context, ComponentName(context, PlaybackService::class.java))` and calls `MediaController.Builder(context, token).buildAsync()`, which returns a `ListenableFuture<MediaController>`. Binding starts the service and calls `onGetSession`. - `MediaController` **implements `Player`**, so `playerView.player = controller` works, and `setMediaItems`, `prepare` and `play` on the controller are forwarded to the session's player. - Calls go through the controller's application thread, like any `Player`. - Release the controller in `onStop` with `MediaController.releaseFuture(future)`. A service with bound controllers cannot be stopped, so leaked controllers keep it alive. - Set the controller on the view inside the future's listener, on the main executor; before the future completes there is no player to call. Playback resumption is off by default. To let a headset button restart the last lesson after the service was destroyed, even after a reboot, declare Media3's `MediaButtonReceiver` in the manifest and implement `MediaSession.Callback.onPlaybackResumption()`. ## Notification and foreground lifecycle | Moment | What Media3 does | |---|---| | Playlist gets items | A media-style notification appears, built from the session and each item's `MediaMetadata` (title, artist, artwork). | | Playback starts | The service is started in the foreground. | | Paused, stopped or failed | Since 1.6.0 it stays in the foreground for up to 10 minutes (`DEFAULT_FOREGROUND_SERVICE_TIMEOUT_MS`), so the learner can resume. | | After that timeout | The service leaves the foreground and the system may destroy it. | | Playlist cleared or player released | The notification is removed. | On API 33 and later the system media controls are populated from the session, so customise them through `MediaMetadata` and the session's media button preferences rather than by rebuilding the notification. On Android 12 and later, a foreground start the system refuses is reported through `MediaSessionService.Listener.onForegroundServiceStartNotAllowedException()`. ## Common failures - **Audio stops on lock**: the player still lives in the activity, or the service lacks the `mediaPlayback` type. - **No lock-screen controls**: the session was never created, or the playlist has no items. - **Service never stops**: an activity's controller was not released. - **Buffering stalls with the screen off on older releases**: before 1.9.0 the player held no wake lock unless the app called `setWakeMode(C.WAKE_MODE_LOCAL)`; since 1.9.0 wake-lock handling is on by default, and `C.WAKE_MODE_NETWORK` adds a Wi-Fi lock for the cases that need one. - **Player leaks after the service stops**: releasing the session does not release its player, so `onDestroy` must call `player.release()` too.

  • How does the lesson screen show video from a player that lives in the service?
    It connects a `MediaController` with a `SessionToken` for the service and sets it on the `PlayerView`. Because the controller implements `Player`, the view attaches its surface and controls through it exactly as with a local ExoPlayer. When the screen stops, release the controller with `MediaController.releaseFuture`; the service keeps playing audio.
  • What happens when the learner swipes the app away from recents?
    Since Media3 1.4.0 the default `onTaskRemoved` keeps the service running if playback is ongoing and a session is playing; otherwise it calls `pauseAllPlayersAndStopSelf()`, which pauses every session's player and stops the service so `onDestroy` releases them. Override it to stop playback whenever the app is dismissed.
  • Why does a paused lesson keep its notification for a while and then lose foreground status?
    Since 1.6.0 a `MediaSessionService` stays in the foreground for up to 10 minutes after playback pauses, stops or fails, so the learner can resume without hitting background-start restrictions. After that timeout it becomes a background service the system may destroy; playback resumption, if implemented, lets the learner restart it later.

Moving the player into the service is like moving the music from a passenger's phone to the car's stereo: it keeps playing when the passenger looks away, and the steering-wheel buttons, the dashboard and every passenger control it through one shared system.

  • Keeping the ExoPlayer in the activity and simply not releasing it gives reliable background playback.
  • The app must build and post its own notification before Media3 can play in the background.
  • MediaSessionService needs no foregroundServiceType, because Media3 sets one at runtime.
  • The UI must cast the MediaController to ExoPlayer to call play or attach a PlayerView.
  • ExoPlayer handles audio focus by default, so a lesson pauses for calls without any setup.
  • Releasing the session alone also releases the player inside it.

Assumes Media3 1.11; the default onTaskRemoved and pauseAllPlayersAndStopSelf arrived in 1.4.0, the 10-minute foreground grace after a pause in 1.6.0, and default wake-lock handling in 1.9.0.