open class MediaSession : Closeable
Allows a media app to expose its transport controls and playback information in a process to other processes including the Android framework and other apps. Common use cases are as follows.
- Bluetooth/wired headset key events support
- Android Auto/Wearable support
- Separating UI process and playback process
A MediaSession should be created when an app wants to publish media playback information or handle media keys. In general an app only needs one session for all playback, though multiple sessions can be created to provide finer grain controls of media. See Supporting Multiple Sessions for detail.
Topics covered here:
- Session Lifecycle
- Media key events mapping
- Supporting Multiple Sessions
- Backward compatibility with legacy session APIs
- Backward compatibility with legacy controller APIs
When an app is finished performing playback it must call #close() to clean up the session and notify any controllers. The app is responsible for closing the underlying player after closing the session. is closed.
MediaSession objects are thread safe, but should be used on the thread on the looper.
Media key events mapping
Here's the table of per key event.
Supporting Multiple SessionsGenerally speaking, multiple sessions aren't necessary for most media apps. One exception is if your app can play multiple media content at the same time, but only for the playback of video-only media or remote playback, since audio focus policy recommends not playing multiple audio content at the same time. Also keep in mind that multiple media sessions would make Android Auto and Bluetooth device with display to show your apps multiple times, because they list up media sessions, not media apps.
Backward compatibility with legacy session APIsAn active
MediaSessionCompatis internally created with the MediaSession for the backward compatibility. It's used to handle incoming connection and command from
MediaControllerCompat. And helps to utilize existing APIs that are built with legacy media session APIs. Use
getSessionCompatTokenfor getting the token for the underlying MediaSessionCompat.
Backward compatibility with legacy controller APIsIn addition to the
media2 controllerAPI, session also supports connection from the legacy controller API -
AndroidX controller compat. However,
ControllerInfomay not be precise for legacy controller. See
ControllerInfofor the details.
Unknown package name nor UID doesn't mean that you should disallow connection nor commands. For SDK levels where such issue happen, session tokens could only be obtained by trusted apps (e.g. Bluetooth, Auto, ...), so it may be better for you to allow them as you did with legacy session.
Button for a
Information of a controller.
Callback to be called for all incoming commands from
Broadcasts a custom command to all connected controllers.
Returns the list of connected controller.
Gets the session ID
Gets the underlying
Sends a custom command to a specific controller.