Added in API level 21

MediaSession

class MediaSession
kotlin.Any
   ↳ android.media.session.MediaSession

Allows interaction with media controllers, volume keys, media buttons, and transport controls.

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.

Once a session is created the owner of the session may pass its session token to other processes to allow them to create a MediaController to interact with the session.

To receive commands, media keys, and other events a Callback must be set with setCallback(android.media.session.MediaSession.Callback) and setActive(true) must be called.

When an app is finished performing playback it must call release() to clean up the session and notify any controllers.

MediaSession objects are thread safe.

Summary

Nested classes
abstract

Receives media buttons, transport controls, and commands from controllers and the system.

A single item that is part of the play queue.

Represents an ongoing session.

Constants
static Int

Set this flag on the session to indicate that it can handle media button events.

static Int

Set this flag on the session to indicate that it handles transport control commands through its Callback.

Public constructors
MediaSession(context: Context, tag: String)

Creates a new session.

MediaSession(context: Context, tag: String, sessionInfo: Bundle?)

Creates a new session.

Public methods
MediaController

Get a controller for this session.

MediaSessionManager.RemoteUserInfo

Gets the controller information who sent the current request.

MediaSession.Token

Retrieve a token object that can be used by apps to create a MediaController for interacting with this session.

Boolean

Get the current active state of this session.

Unit

This must be called when an app has finished performing playback.

Unit
sendSessionEvent(event: String, extras: Bundle?)

Send a proprietary event to all MediaControllers listening to this Session.

Unit
setActive(active: Boolean)

Set if this session is currently active and ready to receive commands.

Unit

Set the callback to receive updates for the MediaSession.

Unit
setCallback(callback: MediaSession.Callback?, handler: Handler?)

Set the callback to receive updates for the MediaSession.

Unit
setExtras(extras: Bundle?)

Set some extras that can be associated with the MediaSession.

Unit
setFlags(flags: Int)

Set any flags for the session.

Unit

Set the component name of the manifest-declared android.content.BroadcastReceiver class that should receive media buttons.

Unit

Set a pending intent for your media button receiver to allow restarting playback after the session has been stopped.

Unit

Update the current metadata.

Unit

Update the current playback state.

Unit

Set the attributes for this session's audio.

Unit

Configure this session to use remote volume handling.

Unit

Update the list of items in the play queue.

Unit

Set the title of the play queue.

Unit

Set the style of rating used by this session.

Unit

Set an intent for launching UI for this Session.

Constants

FLAG_HANDLES_MEDIA_BUTTONS

Added in API level 21
Deprecated in API level 26
static val FLAG_HANDLES_MEDIA_BUTTONS: Int

Deprecated: This flag is no longer used. All media sessions are expected to handle media button events now.

Set this flag on the session to indicate that it can handle media button events.

Value: 1

FLAG_HANDLES_TRANSPORT_CONTROLS

Added in API level 21
Deprecated in API level 26
static val FLAG_HANDLES_TRANSPORT_CONTROLS: Int

Deprecated: This flag is no longer used. All media sessions are expected to handle transport controls now.

Set this flag on the session to indicate that it handles transport control commands through its Callback.

Value: 2

Public constructors

MediaSession

Added in API level 21
MediaSession(
    context: Context,
    tag: String)

Creates a new session. The session will automatically be registered with the system but will not be published until setActive(true) is called. You must call release() when finished with the session.

Note that RuntimeException will be thrown if an app creates too many sessions.

Parameters
context Context: The context to use to create the session. This value cannot be null.
tag String: A short name for debugging purposes. This value cannot be null.

MediaSession

Added in API level 21
MediaSession(
    context: Context,
    tag: String,
    sessionInfo: Bundle?)

Creates a new session. The session will automatically be registered with the system but will not be published until setActive(true) is called. You must call release() when finished with the session.

The sessionInfo can include additional unchanging information about this session. For example, it can include the version of the application, or the list of the custom commands that this session supports.

Note that RuntimeException will be thrown if an app creates too many sessions.

Parameters
context Context: The context to use to create the session. This value cannot be null.
tag String: A short name for debugging purposes. This value cannot be null.
sessionInfo Bundle?: A bundle for additional information about this session. Controllers can get this information by calling MediaController#getSessionInfo(). An IllegalArgumentException will be thrown if this contains any non-framework Parcelable objects. This value may be null.

Public methods

getController

Added in API level 21
fun getController(): MediaController

Get a controller for this session. This is a convenience method to avoid having to cache your own controller in process.

Return
MediaController A controller for this session. This value cannot be null.

getCurrentControllerInfo

Added in API level 28
fun getCurrentControllerInfo(): MediaSessionManager.RemoteUserInfo

Gets the controller information who sent the current request.

Note: This is only valid while in a request callback, such as Callback#onPlay.

Return
MediaSessionManager.RemoteUserInfo This value cannot be null.
Exceptions
java.lang.IllegalStateException If this method is called outside of Callback methods.

getSessionToken

Added in API level 21
fun getSessionToken(): MediaSession.Token

Retrieve a token object that can be used by apps to create a MediaController for interacting with this session. The owner of the session is responsible for deciding how to distribute these tokens.

Return
MediaSession.Token A token that can be used to create a MediaController for this session This value cannot be null.

isActive

Added in API level 21
fun isActive(): Boolean

Get the current active state of this session.

Return
Boolean True if the session is active, false otherwise.

release

Added in API level 21
fun release(): Unit

This must be called when an app has finished performing playback. If playback is expected to start again shortly the session can be left open, but it must be released if your activity or service is being destroyed.

sendSessionEvent

Added in API level 21
fun sendSessionEvent(
    event: String,
    extras: Bundle?
): Unit

Send a proprietary event to all MediaControllers listening to this Session. It's up to the Controller/Session owner to determine the meaning of any events.

Parameters
event String: The name of the event to send This value cannot be null.
extras Bundle?: Any extras included with the event This value may be null.

setActive

Added in API level 21
fun setActive(active: Boolean): Unit

Set if this session is currently active and ready to receive commands. If set to false your session's controller may not be discoverable. You must set the session to active before it can start receiving media button events or transport commands.

Parameters
active Boolean: Whether this session is active or not.

setCallback

Added in API level 21
fun setCallback(callback: MediaSession.Callback?): Unit

Set the callback to receive updates for the MediaSession. This includes media button events and transport controls. The caller's thread will be used to post updates.

Set the callback to null to stop receiving updates.

Parameters
callback MediaSession.Callback?: The callback object This value may be null.

setCallback

Added in API level 21
fun setCallback(
    callback: MediaSession.Callback?,
    handler: Handler?
): Unit

Set the callback to receive updates for the MediaSession. This includes media button events and transport controls.

Set the callback to null to stop receiving updates.

Parameters
callback MediaSession.Callback?: The callback to receive updates on. This value may be null.
handler Handler?: The handler that events should be posted on. This value may be null.

setExtras

Added in API level 21
fun setExtras(extras: Bundle?): Unit

Set some extras that can be associated with the MediaSession. No assumptions should be made as to how a MediaController will handle these extras. Keys should be fully qualified (e.g. com.example.MY_EXTRA) to avoid conflicts.

Parameters
extras Bundle?: The extras associated with the MediaSession. This value may be null.

setFlags

Added in API level 21
fun setFlags(flags: Int): Unit

Set any flags for the session.

Parameters
flags Int: The flags to set for this session. Value is either 0 or a combination of android.media.session.MediaSession#FLAG_HANDLES_MEDIA_BUTTONS, android.media.session.MediaSession#FLAG_HANDLES_TRANSPORT_CONTROLS, and android.media.session.MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY

setMediaButtonBroadcastReceiver

Added in API level 31
fun setMediaButtonBroadcastReceiver(broadcastReceiver: ComponentName?): Unit

Set the component name of the manifest-declared android.content.BroadcastReceiver class that should receive media buttons. This allows restarting playback after the session has been stopped. If your app is started in this way an Intent#ACTION_MEDIA_BUTTON intent will be sent to the broadcast receiver. On apps targeting Android U and above, this will throw an IllegalArgumentException if the provided ComponentName does not resolve to an existing broadcast receiver.

Note: The given android.content.BroadcastReceiver should belong to the same package as the context that was given when creating MediaSession.

Parameters
broadcastReceiver ComponentName?: the component name of the BroadcastReceiver class This value may be null.
Exceptions
java.lang.IllegalArgumentException if broadcastReceiver does not exist on apps targeting Android U and above

setMediaButtonReceiver

Added in API level 21
Deprecated in API level 31
fun setMediaButtonReceiver(mbr: PendingIntent?): Unit

Deprecated: Use setMediaButtonBroadcastReceiver(android.content.ComponentName) instead.

Set a pending intent for your media button receiver to allow restarting playback after the session has been stopped.

If your app is started in this way an Intent#ACTION_MEDIA_BUTTON intent will be sent via the pending intent.

The provided PendingIntent must not target an activity. On apps targeting Android V and above, passing an activity pending intent to this method causes an IllegalArgumentException. On apps targeting Android U and below, passing an activity pending intent causes the call to be ignored. Refer to this guide for more information.

The pending intent is recommended to be explicit to follow the security recommendation of PendingIntent#getService.

Parameters
mbr PendingIntent?: The PendingIntent to send the media button event to. This value may be null.
Exceptions
java.lang.IllegalArgumentException if the pending intent targets an activity on apps targeting Android V and above.

setMetadata

Added in API level 21
fun setMetadata(metadata: MediaMetadata?): Unit

Update the current metadata. New metadata can be created using android.media.MediaMetadata.Builder. This operation may take time proportional to the size of the bitmap to replace large bitmaps with a scaled down copy.

Parameters
metadata MediaMetadata?: The new metadata This value may be null.

setPlaybackState

Added in API level 21
fun setPlaybackState(state: PlaybackState?): Unit

Update the current playback state.

Parameters
state PlaybackState?: The current state of playback This value may be null.

setPlaybackToLocal

Added in API level 21
fun setPlaybackToLocal(attributes: AudioAttributes!): Unit

Set the attributes for this session's audio. This will affect the system's volume handling for this session. If setPlaybackToRemote was previously called it will stop receiving volume commands and the system will begin sending volume changes to the appropriate stream.

By default sessions use attributes for media.

Parameters
attributes AudioAttributes!: The AudioAttributes for this session's audio.

setPlaybackToRemote

Added in API level 21
fun setPlaybackToRemote(volumeProvider: VolumeProvider): Unit

Configure this session to use remote volume handling. This must be called to receive volume button events, otherwise the system will adjust the appropriate stream volume for this session. If setPlaybackToLocal was previously called the system will stop handling volume changes for this session and pass them to the volume provider instead.

Parameters
volumeProvider VolumeProvider: The provider that will handle volume changes. May not be null.

setQueue

Added in API level 21
fun setQueue(queue: MutableList<MediaSession.QueueItem!>?): Unit

Update the list of items in the play queue. It is an ordered list and should contain the current item, and previous or upcoming items if they exist. Specify null if there is no current play queue.

The queue should be of reasonable size. If the play queue is unbounded within your app, it is better to send a reasonable amount in a sliding window instead.

Parameters
queue MutableList<MediaSession.QueueItem!>?: A list of items in the play queue. This value may be null.

setQueueTitle

Added in API level 21
fun setQueueTitle(title: CharSequence?): Unit

Set the title of the play queue. The UI should display this title along with the play queue itself. e.g. "Play Queue", "Now Playing", or an album name.

Parameters
title CharSequence?: The title of the play queue. This value may be null.

setSessionActivity

Added in API level 21
fun setSessionActivity(pi: PendingIntent?): Unit

Set an intent for launching UI for this Session. This can be used as a quick link to an ongoing media screen. The intent should be for an activity that may be started using android.app.Activity#startActivity(android.content.Intent).

Parameters
pi PendingIntent?: The intent to launch to show UI for this Session. This value may be null.