In this post, we'll learn about Android MediaSession API, why we should use it, and how to implement it on Android TV (or Fire TV) apps. After setting the ground, we'll follow a step-by-step guide on a basic MediaSession implementation. The sample app used for this article and all the code below can be found here.
If you need to become more familiar with or need a recap on how playback controls are implemented using the Leanback components, check my previous articles. I cover from the basics to further customizations on the Leanback playback controls.
What is a MediaSession?
As per the documentation, a MediaSession "Allows interaction with media controllers, volume keys, media buttons, and transport controls". More than that, a MediaSession is the control center where we can read information about what is currently being played on the Android device and dispatch media control actions such as play, pause, rewind, skip, seek, and more.
From an active MediaSession, the Android system can control an app's media playback and query information about it. Whenever you send, for example, a play/pause command by pressing or tapping on your earbuds, you are triggering MediaSession callbacks that ask the underlying player app to perform those actions.
On the other hand, a music or video app should provide information about what's currently playing to an active MediaSession. This is how the Android system can display this data to the user and provide interfaces where the user can dispatch media actions—for example, using on-screen buttons or sending voice commands through Google Assistant or Amazon Alexa.