Design a video player screen
The question
Design a video player screen for a streaming app where the user can play HLS or DASH streams, seek, switch quality, use picture-in-picture, and continue playback in the background. Walk me through the architecture, lifecycle handling, and how you keep the player alive across configuration changes.
Clarify before you design:
- Is this a single full-screen player, or a list of videos with a detail player screen?
- Do we need to support both HLS and DASH, or just one adaptive format?
- Is offline playback (explicit downloads) in scope, or only caching what was already watched?
- Does "background" mean audio keeps playing with the screen off, or only picture-in-picture?
- What is the minimum API level?
PictureInPictureParamsneeds API 26, and auto-enter PiP needs Android 12. - Do we need DRM (Widevine) for protected content?
- After process death, is it fine to resume from the last saved position?
- Do we need multi-window or split-screen support on tablets and foldables?
Requirements
Functional
- Play, pause, seek, and stop an HLS or DASH stream with adaptive bitrate selection.
- Show a quality selector built from the video tracks in
player.currentTracks. - Support picture-in-picture so the video floats over other apps.
- Continue playback in the background through a
MediaSessionService, with a media notification and lock-screen controls. - Persist and restore playback position so the user resumes where they left off.
- Cache watched segments, and let the user download a video for offline viewing.
Non-functional
- Battery: when nothing is visible and background playback is not active, pause or release the player so it stops decoding and gives up audio focus.
- Memory: the player and its decoders are released when playback is truly finished, not just paused.
- Startup: time to first frame is a tracked metric. Set a target with the product team, measure it on real devices and networks, and tune buffering only after measuring.
- Offline: downloaded videos play with no network, and the UI shows a "Downloaded" badge.
- Privacy: playback position and watch history are stored locally in Room; no telemetry is sent without consent.
- Stability: no crash or leak on rapid rotation, PiP toggle, or process death.
Out of scope
- DRM license acquisition and Widevine provisioning.
- Server-side encoding and the bitrate ladder; the client only picks from what the manifest offers.
- Multi-device sync of watch progress.
High-level architecture
The screen has three layers: UI, state, and a playback service.
Playback service. A PlaybackService extends Media3's MediaSessionService. It owns the single ExoPlayer and a MediaSession wrapping it. Because the player lives in a service and not in the Activity, rotation, PiP and leaving the app do not touch it. Media3 posts the media notification and moves the service in and out of the foreground for you. The manifest declares the service with foregroundServiceType="mediaPlayback", and on Android 14+ the app also needs the FOREGROUND_SERVICE_MEDIA_PLAYBACK permission.
UI layer. A Compose VideoPlayerScreen connects to the session with a MediaController built from a SessionToken. MediaController implements Player, so the UI uses it like a player. The video surface is either PlayerView (from media3-ui) inside AndroidView, or PlayerSurface / ContentFrame from the media3-ui-compose artifact. The controller is connected in onStart and released in onStop. That is cheap: only the connection is rebuilt, never the player.
State layer. A PlayerViewModel loads video metadata and stream URLs from a VideoRepository and exposes StateFlow<PlaybackUiState> (title, available qualities, error, downloaded flag). Errors and "playback ended" are fields in that state, not one-off events. Live player values like position come from the controller.
Data flow. User intent → MediaController → MediaSession → ExoPlayer → Player.Listener callbacks → UI. Metadata flows Retrofit → Room → ViewModel → UI.
Threading. An ExoPlayer must be used from one application thread (the main thread by default), and its listener callbacks arrive on that thread. Loading and decoding happen on internal threads, so you do not wrap player calls in withContext. Retrofit and Room suspend calls are already main-safe.
| Component | Responsibility |
|---|---|
| VideoPlayerScreen (Compose) | Renders the video surface and controls. Connects a MediaController in onStart, releases it in onStop. Handles PiP mode. No business logic. |
| PlayerViewModel | Loads metadata through the repository. Exposes StateFlow<PlaybackUiState> with qualities, errors and download state. |
PlaybackService (MediaSessionService) | Owns the ExoPlayer and MediaSession. Media3 handles the notification and foreground state. Saves the playback position. Releases everything in onDestroy. |
| VideoRepository | Fetches metadata and stream URLs via Retrofit, stores them in Room, reads and writes playback positions. |
| ExoPlayer + DefaultMediaSourceFactory | Picks HLS or DASH automatically when media3-exoplayer-hls / media3-exoplayer-dash are on the classpath. Handles adaptive bitrate, buffering, audio focus and becoming-noisy when configured. |
| PlaybackPositionDao (Room) | Stores the last position per video. Written every few seconds while playing and when playback pauses. |
| SimpleCache + CacheDataSource | One SimpleCache singleton per cache directory. CacheDataSource.Factory reads cached data first and falls back to the network. |
| DownloadManager + DownloadService | Media3 download stack for explicit offline downloads. Tracks downloads in its own index. |
Data model and API
@Entity(tableName = "videos")
data class VideoEntity(
@PrimaryKey val id: String,
val title: String,
val streamUrl: String, // .m3u8 (HLS) or .mpd (DASH)
val thumbnailUrl: String,
val durationMs: Long
)
@Entity(tableName = "playback_positions")
data class PlaybackPositionEntity(
@PrimaryKey val videoId: String,
val positionMs: Long,
val updatedAt: Long
)
data class VideoDto(
val id: String,
val title: String,
val streams: List<StreamDto>,
val thumbnail: String,
val durationMs: Long
)
data class StreamDto(
val format: String, // "hls" or "dash"
val url: String
)
data class QualityOption(val height: Int, val bitrate: Int)
data class PlaybackUiState(
val title: String = "",
val qualities: List<QualityOption> = emptyList(),
val selectedHeight: Int? = null, // null means automatic
val isDownloaded: Boolean = false,
val errorMessage: String? = null,
val isEnded: Boolean = false
)
interface VideoRepository {
suspend fun getVideo(id: String): VideoEntity
suspend fun getSavedPosition(videoId: String): Long?
suspend fun savePosition(videoId: String, positionMs: Long)
}The playback service is small. Media3 does the foreground and notification work:
@OptIn(UnstableApi::class)
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_MOVIE)
.build()
val player = ExoPlayer.Builder(this)
.setMediaSourceFactory(
DefaultMediaSourceFactory(this)
.setDataSourceFactory(AppMedia.cacheDataSourceFactory(this))
)
.setAudioAttributes(audioAttributes, /* handleAudioFocus = */ true)
.setHandleAudioBecomingNoisy(true)
.build()
mediaSession = MediaSession.Builder(this, player).build()
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
mediaSession
override fun onTaskRemoved(rootIntent: Intent?) {
pauseAllPlayersAndStopSelf()
}
override fun onDestroy() {
mediaSession?.run {
player.release()
release()
mediaSession = null
}
super.onDestroy()
}
}AppMedia stands for your own singleton (or Hilt module) that holds the one SimpleCache and builds the CacheDataSource.Factory.
The UI connects only while it is started:
@Composable
fun rememberMediaController(): MediaController? {
val context = LocalContext.current
var controller by remember { mutableStateOf<MediaController?>(null) }
LifecycleStartEffect(Unit) {
val token = SessionToken(context, ComponentName(context, PlaybackService::class.java))
val future = MediaController.Builder(context, token).buildAsync()
future.addListener(
{
if (!future.isCancelled) {
try {
controller = future.get()
} catch (e: ExecutionException) {
// Could not connect to the session; leave controller null.
}
}
},
ContextCompat.getMainExecutor(context)
)
onStopOrDispose {
controller = null
MediaController.releaseFuture(future)
}
}
return controller
}Deep dives
Player Lifecycle and Configuration Changes
If you create an ExoPlayer inside a composable with remember, or in onCreate, rotation destroys it. The user sees a black frame, the buffer is lost, and the stream is fetched again.
There are two honest options:
- Foreground-only playback. The Media3 guidance for a player owned by the Activity is: on API 24+, create it in
onStartand release it inonStop, because the Activity can still be visible in multi-window or PiP afteronPause. Restore the position on the nextonStart. To avoid re-buffering on rotation, hold the player in aViewModelinstead, attach it to the surface inonStart, pause it inonStop, and release it inonCleared. The trade-off is that a paused player still holds its decoders and buffer while the app is in the background. - Background playback. Put the player in a
MediaSessionServiceand connect from the UI with aMediaController. Rotation only reconnects the controller; the player, its buffer and the notification are untouched. This is the design here, because the requirements include background playback.
Process death kills the service and the player too. Save the video id and position to Room every few seconds while playing and when playback pauses. On the next launch, the ViewModel reads them and the UI calls setMediaItem, seekTo(savedPosition) and prepare(). Keeping the video id in SavedStateHandle (or the navigation route) lets the restored screen know which video it showed. Test by rotating mid-playback, and by backgrounding the app and running adb shell am kill <package>.
Background Playback with MediaSessionService
When the user presses Home or locks the screen, the Activity gets onStop. A player owned by the Activity stops there. For background playback, you subclass MediaSessionService, build the ExoPlayer and MediaSession in onCreate, return the session from onGetSession, and release both in onDestroy.
Declare the service in the manifest with an intent filter for androidx.media3.session.MediaSessionService and android:foregroundServiceType="mediaPlayback". Add the FOREGROUND_SERVICE and FOREGROUND_SERVICE_MEDIA_PLAYBACK permissions (the second is required when targeting Android 14+). On Android 13+, notifications from a media session are exempt from the POST_NOTIFICATIONS runtime permission.
You do not build a MediaStyle notification yourself. Media3 creates the media notification from the session, promotes the service to the foreground while playing, and lets the service stop being foreground when playback pauses or ends. The same session drives lock-screen controls, Bluetooth buttons and system media controls.
By default, if the user swipes the app away from recents, the service keeps running when playback is ongoing and stops otherwise. Override onTaskRemoved if you want a different rule. Calling pauseAllPlayersAndStopSelf() pauses and stops the service.
Adaptive Streaming and Offline
Add media3-exoplayer-hls and/or media3-exoplayer-dash. Then MediaItem.fromUri(url) is enough: DefaultMediaSourceFactory picks the right media source from the URL or MIME type. You only build HlsMediaSource.Factory or DashMediaSource.Factory by hand when you need special configuration.
The default DefaultTrackSelector picks a video track from the measured bandwidth and the device's capabilities, and switches during playback. For a quality menu, read the video groups from player.currentTracks. To cap quality, update player.trackSelectionParameters with setMaxVideoSize or setMaxVideoBitrate. To pin one track, use setOverrideForType(TrackSelectionOverride(...)). "Auto" means clearing that override. Changing the parameters goes through the Player interface, so it also works from a MediaController.
There are two different features here:
- Cache of watched content. One
SimpleCachewith aLeastRecentlyUsedCacheEvictorand a size limit, wrapped byCacheDataSource.Factory. It cuts data use on re-watch, but entries can be evicted at any time, so it does not guarantee offline playback. - Explicit downloads. Media3's
DownloadManagerand aDownloadServicesubclass.DownloadHelperresolves an HLS or DASH manifest into aDownloadRequestfor the chosen tracks. The download cache usesNoOpCacheEvictor, because downloads must not be evicted. TheDownloadServiceis a foreground service of typedataSync. ASchedulersuch asWorkManagerSchedulerrestarts downloads when requirements like unmetered network are met. For playback, point a read-onlyCacheDataSource.Factory(cache writes disabled) at the download cache.
SimpleCache needs a DatabaseProvider such as StandaloneDatabaseProvider, and only one SimpleCache instance may use a given directory at a time. Creating a second one on the same folder throws. Make it an app-wide singleton and share it between players. The "Downloaded" badge comes from the DownloadManager's download index and its listener, not from guessing at cache contents. If the user clears app storage, the index and files go together, so the badge stays consistent.
Picture-in-Picture and Audio Focus
Declare android:supportsPictureInPicture="true" on the Activity. Also declare configChanges for screen size, smallest screen size, screen layout and orientation, so entering and leaving PiP does not recreate the Activity. The PiP API needs API 26.
- On Android 12+, call
setPictureInPictureParamswithsetAutoEnterEnabled(true)while video is playing. The system then enters PiP smoothly when the user goes home. Turn it off when playback stops. - On Android 8 to 11, call
enterPictureInPictureMode(params)fromonUserLeaveHint(). - Set
setAspectRatio(Rational(videoWidth, videoHeight))from the video size. The platform only accepts ratios between about 2.39:1 and 1:2.39, so clamp extreme values. AddsetSourceRectHintwith the video bounds for a clean animation. - In PiP, hide the controls and show only the video. Listen for PiP mode changes (
onPictureInPictureModeChanged, oraddOnPictureInPictureModeChangedListeneron aComponentActivity).
In PiP the Activity is paused but still started, so never pause video in onPause. That is another reason to tie playback to onStart / onStop.
For audio focus, configure the player with setAudioAttributes(attrs, handleAudioFocus = true), using C.USAGE_MEDIA and C.AUDIO_CONTENT_TYPE_MOVIE. ExoPlayer then requests focus when playback starts and abandons it when it stops. On a permanent loss (another app starts music) it pauses and stays paused. On a transient loss (a phone call) it pauses and resumes when focus comes back. When another app asks it to duck, it lowers the volume instead of pausing (except for speech content). Also call setHandleAudioBecomingNoisy(true), so playback pauses when headphones are unplugged.
Managing AudioManager.requestAudioFocus yourself is possible, but easy to get wrong. PiP and background playback are separate concerns: PiP is a window mode of the Activity, and the service keeps the player alive either way.
Trade-offs
| Decision | Options | What to pick and why |
|---|---|---|
| Player ownership | Composable remember, Activity, ViewModel, MediaSessionService. | With background playback, use a MediaSessionService and a MediaController in the UI. Rotation and PiP never touch the player, and Media3 handles the notification. For foreground-only playback, a ViewModel (pause in onStop, release in onCleared) or the Activity (create in onStart, release in onStop) is simpler. A player in a composable is lost on rotation. |
| Caching | No cache, SimpleCache cache of watched content, explicit downloads with DownloadManager. | Use an LRU SimpleCache for re-watch savings, plus DownloadManager and DownloadService for guaranteed offline. Keep the two caches in separate directories: the LRU cache evicts, the download cache must not. |
| Video surface | PlayerView in AndroidView, media3-ui-compose (PlayerSurface, ContentFrame), your own SurfaceView or TextureView. | PlayerView is the most complete: controls, subtitles, aspect-ratio fitting. media3-ui-compose fits a fully custom Compose UI. Prefer SurfaceView over TextureView for power and smoothness; use TextureView only when you need to animate, scale or alpha-blend the video view itself. |
| State delivery to UI | Player.Listener in the UI, StateFlow<PlaybackUiState> from the ViewModel. | Use the ViewModel's StateFlow for screen state (qualities, errors, ended, downloaded), with errors and "ended" as state fields the UI clears after showing. Read live position and play state from the controller, or with the media3-ui-compose state holders. |
| PiP trigger | Automatic on leaving the app, a PiP button, both. | Both. Auto-enter (setAutoEnterEnabled on 12+, onUserLeaveHint before that) only while video is playing, plus a button in the controls. Some apps let users turn auto-PiP off. |
What breaks in production
- After users watched several videos in a row, some devices failed to start playback with decoder initialization errors, and memory kept growing.
- The detail screen created an
ExoPlayerwithrememberfor every video and never calledrelease(). Each leaked player kept its codecs, buffers and threads. - Hardware decoders are a limited, device-specific resource, so the failure showed up only on some devices.
- Keep one player (in the service) and reuse it with
setMediaItemfor the next video, instead of building a new one. - If a screen does own a player, release it in
onStop,onClearedor aDisposableEffect'sonDispose, and always release it in the service'sonDestroy. - Add LeakCanary to debug builds, and test playing many videos in a row on a low-end device.
- Users reported that their music app stopped and never recovered after they watched a clip, or that the video and music played on top of each other.
- The player was built with
handleAudioFocus = false. A manualrequestAudioFocuscall ran on play, but the focus was never abandoned on pause or stop, and focus-loss callbacks were ignored.
- Use
setAudioAttributes(attrs, handleAudioFocus = true)so ExoPlayer requests and abandons focus with playback, and reacts to focus loss. - If you must manage focus by hand, abandon it whenever playback pauses or stops, and handle every focus-change type.
- Add a manual test: play music, start a video, stop it from the notification, and check the music app's behaviour. Repeat with an incoming call.
Common mistakes in this round
- Creating ExoPlayer inside a composable or in onCreate. Rotation destroys it. The user sees a black frame, the buffer is lost and the stream is fetched again.
- Never releasing the player. A leaked player holds codecs, buffers and threads. On devices with few hardware decoders, the next player can fail to start.
- Pausing in onPause. In PiP and multi-window the Activity is paused but still visible. Pause or release in
onStopinstead. - Background playback without a MediaSessionService. Without a foreground service, background playback can be stopped when the system reclaims the process. Without a session, there are no lock-screen, notification or headset controls.
- Building the media notification and foreground logic by hand. Media3's
MediaSessionServicealready does it. Hand-rolled code often misses the Android 14 foreground service type rules. - Not configuring audio focus or becoming-noisy. Two apps play at once, or the video keeps blasting through the speaker after headphones are unplugged.
- Treating the LRU cache as offline support. Cached entries can be evicted at any time. Guaranteed offline needs
DownloadManagerwith a non-evicting cache. - Two SimpleCache instances on one folder. This throws. Keep one app-wide instance per directory.
Follow-up questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens to the player when the user rotates the device?”
“How do you handle the case where the user locks the phone while a video is playing?”
“How would you support offline playback?”
“How do you handle audio focus when another app starts playing music?”
Self-review checklist
- The player lives outside Activity recreation: in a
MediaSessionServicefor background playback, or aViewModelfor foreground-only playback. - The UI connects a
MediaController(from aSessionToken) inonStartand releases it inonStop. - The service declares
foregroundServiceType="mediaPlayback", the Android 14 type permission and theMediaSessionServiceintent filter, and releases the player and session inonDestroy. - HLS and DASH come from the
media3-exoplayer-hls/-dashmodules throughDefaultMediaSourceFactory. - Quality selection uses
trackSelectionParameters(max size, max bitrate or a track override). - One
SimpleCacheper directory with aStandaloneDatabaseProvider. Downloads useDownloadManager,DownloadServiceand a non-evicting cache. - Audio focus via
setAudioAttributes(attrs, true), plussetHandleAudioBecomingNoisy(true). - PiP uses
setAutoEnterEnabledon Android 12+ oronUserLeaveHintbefore that, with a clamped aspect ratio, and playback is not paused inonPause. - Playback position is saved to Room periodically and restored after process death.