Understanding MediaSession (Part 3/4)
How to use it for simple use cases
Introduction
The goal of this series of articles is to give you a deep understanding of MediaSession
, what it is good for, when to use it, and when not to. This is the third part of a 4 part series that includes:
- Is MediaSession for me?
- Making sense of the complex media landscape
- How to use it for simple use cases (this article)
- How to use it for complex use cases
How to use it
Now that we have covered a high level conceptual model of what MediaSession
is, why to it, and how it roughly fits into your app’s codebase, here are some details on how to use it. We are going to cover two use cases for media playback apps:
- An video playback app that only supports foreground playback.
- An audio playback app that supports both foreground and background playback, and allows other apps to browse its media content.
App that plays video in the foreground
This app has a UI that allows the user to control audio playback. And it can use a MediaSession
to communicate information between the player and the activity. However, it does not have a Service
, and neither does it use MediaBrowserService
, not does it show notifications.
The diagram below provides a high level overview of the components that you have to implement in order to create an audio playback app that uses MediaSession
.
Please refer to developers.android.com to get more details on each of the classes that you will need to use. You will have to perform the following tasks:
- Create a
MediaPlayer
orExoPlayer
to actually load, prepare, and play the content. - Create a
MediaSession
that you can use to share information about what is playing to other apps. And you can also allow external playback control of your app (from Google Assistant, Bluetooth headsets, media buttons, etc).
The next article in the series covers this in much greater detail for the more complex use case of playing audio in the background.