Understanding MediaSession (Part 3/4)

How to use it for simple use cases


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:

  1. Is MediaSession for me?
  2. Making sense of the complex media landscape
  3. How to use it for simple use cases (this article)
  4. 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:

  1. An video playback app that only supports foreground playback.
  2. 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 or ExoPlayer 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.

Android Media Resources

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.