Most visited

Recently visited

MediaSessionCompat

public class MediaSessionCompat
extends Object

java.lang.Object
   ↳ android.support.v4.media.session.MediaSessionCompat


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 MediaControllerCompat to interact with the session.

To receive commands, media keys, and other events a MediaSessionCompat.Callback must be set with setCallback(Callback).

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

MediaSessionCompat objects are not thread safe and all calls should be made from the same thread.

This is a helper for accessing features in MediaSession introduced after API level 4 in a backwards compatible fashion.

Summary

Nested classes

class MediaSessionCompat.Callback

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

interface MediaSessionCompat.OnActiveChangeListener

 

class MediaSessionCompat.QueueItem

A single item that is part of the play queue. 

class MediaSessionCompat.Token

Represents an ongoing session. 

Constants

int FLAG_HANDLES_MEDIA_BUTTONS

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

int FLAG_HANDLES_TRANSPORT_CONTROLS

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

Public constructors

MediaSessionCompat(Context context, String tag)

Creates a new session.

MediaSessionCompat(Context context, String tag, ComponentName mbrComponent, PendingIntent mbrIntent)

Creates a new session with a specified media button receiver (a component name and/or a pending intent).

Public methods

void addOnActiveChangeListener(MediaSessionCompat.OnActiveChangeListener listener)

Adds a listener to be notified when the active status of this session changes.

MediaControllerCompat getController()

Get a controller for this session.

Object getMediaSession()

Gets the underlying framework MediaSession object.

Object getRemoteControlClient()

Gets the underlying framework RemoteControlClient object.

MediaSessionCompat.Token getSessionToken()

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

boolean isActive()

Get the current active state of this session.

static MediaSessionCompat obtain(Context context, Object mediaSession)

Obtain a compat wrapper for an existing MediaSession.

void release()

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

void removeOnActiveChangeListener(MediaSessionCompat.OnActiveChangeListener listener)

Stops the listener from being notified when the active status of this session changes.

void sendSessionEvent(String event, Bundle extras)

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

void setActive(boolean active)

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

void setCallback(MediaSessionCompat.Callback callback, Handler handler)

Set the callback to receive updates for the MediaSession.

void setCallback(MediaSessionCompat.Callback callback)

Add a callback to receive updates on for the MediaSession.

void setExtras(Bundle extras)

Set some extras that can be associated with the MediaSessionCompat.

void setFlags(int flags)

Set any flags for the session.

void setMediaButtonReceiver(PendingIntent mbr)

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

void setMetadata(MediaMetadataCompat metadata)

Update the current metadata.

void setPlaybackState(PlaybackStateCompat state)

Update the current playback state.

void setPlaybackToLocal(int stream)

Set the stream this session is playing on.

void setPlaybackToRemote(VolumeProviderCompat volumeProvider)

Configure this session to use remote volume handling.

void setQueue(List<MediaSessionCompat.QueueItem> queue)

Update the list of items in the play queue.

void setQueueTitle(CharSequence title)

Set the title of the play queue.

void setRatingType(int type)

Set the style of rating used by this session.

void setSessionActivity(PendingIntent pi)

Set an intent for launching UI for this Session.

Inherited methods

From class java.lang.Object

Constants

FLAG_HANDLES_MEDIA_BUTTONS

int FLAG_HANDLES_MEDIA_BUTTONS

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

Constant Value: 1 (0x00000001)

FLAG_HANDLES_TRANSPORT_CONTROLS

int FLAG_HANDLES_TRANSPORT_CONTROLS

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

Constant Value: 2 (0x00000002)

Public constructors

MediaSessionCompat

MediaSessionCompat (Context context, 
                String tag)

Creates a new session. You must call release() when finished with the session.

The session will automatically be registered with the system but will not be published until setActive(true) is called.

For API 20 or earlier, note that a media button receiver is required for handling ACTION_MEDIA_BUTTON. This constructor will attempt to find an appropriate BroadcastReceiver from your manifest. See MediaButtonReceiver for more details.

Parameters
context Context: The context to use to create the session.
tag String: A short name for debugging purposes.

MediaSessionCompat

MediaSessionCompat (Context context, 
                String tag, 
                ComponentName mbrComponent, 
                PendingIntent mbrIntent)

Creates a new session with a specified media button receiver (a component name and/or a pending intent). You must call release() when finished with the session.

The session will automatically be registered with the system but will not be published until setActive(true) is called. Note that mbrComponent and mrbIntent are only used for API 20 or earlier. If you want to set a media button receiver in API 21 or later, call setMediaButtonReceiver(PendingIntent).

For API 20 or earlier, the new session will use the given mbrComponent. If null, this will attempt to find an appropriate BroadcastReceiver that handles ACTION_MEDIA_BUTTON from your manifest. See MediaButtonReceiver for more details.

Parameters
context Context: The context to use to create the session.
tag String: A short name for debugging purposes.
mbrComponent ComponentName: The component name for your media button receiver.
mbrIntent PendingIntent: The PendingIntent for your receiver component that handles media button events. This is optional and will be used on between JELLY_BEAN_MR2 and KITKAT_WATCH instead of the component name.

Public methods

addOnActiveChangeListener

void addOnActiveChangeListener (MediaSessionCompat.OnActiveChangeListener listener)

Adds a listener to be notified when the active status of this session changes. This is primarily used by the support library and should not be needed by apps.

Parameters
listener MediaSessionCompat.OnActiveChangeListener: The listener to add.

getController

MediaControllerCompat getController ()

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

Returns
MediaControllerCompat A controller for this session.

getMediaSession

Object getMediaSession ()

Gets the underlying framework MediaSession object.

This method is only supported on API 21+.

Returns
Object The underlying MediaSession object, or null if none.

getRemoteControlClient

Object getRemoteControlClient ()

Gets the underlying framework RemoteControlClient object.

This method is only supported on APIs 14-20. On API 21+ getMediaSession() should be used instead.

Returns
Object The underlying RemoteControlClient object, or null if none.

getSessionToken

MediaSessionCompat.Token getSessionToken ()

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

On platform versions before LOLLIPOP this token may only be used within your app as there is no way to guarantee other apps are using the same version of the support library.

Returns
MediaSessionCompat.Token A token that can be used to create a media controller for this session.

isActive

boolean isActive ()

Get the current active state of this session.

Returns
boolean True if the session is active, false otherwise.

obtain

MediaSessionCompat obtain (Context context, 
                Object mediaSession)

Obtain a compat wrapper for an existing MediaSession.

Parameters
context Context
mediaSession Object: The MediaSession to wrap.
Returns
MediaSessionCompat A compat wrapper for the provided session.

release

void release ()

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.

removeOnActiveChangeListener

void removeOnActiveChangeListener (MediaSessionCompat.OnActiveChangeListener listener)

Stops the listener from being notified when the active status of this session changes.

Parameters
listener MediaSessionCompat.OnActiveChangeListener: The listener to remove.

sendSessionEvent

void sendSessionEvent (String event, 
                Bundle extras)

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
extras Bundle: Any extras included with the event

setActive

void setActive (boolean active)

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.

On platforms earlier than LOLLIPOP, a media button event receiver should be set via the constructor to receive media button events.

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

setCallback

void setCallback (MediaSessionCompat.Callback callback, 
                Handler handler)

Set the callback to receive updates for the MediaSession. This includes media button and volume events. Set the callback to null to stop receiving events.

Parameters
callback MediaSessionCompat.Callback: The callback to receive updates on.
handler Handler: The handler that events should be posted on.

setCallback

void setCallback (MediaSessionCompat.Callback callback)

Add a callback to receive updates on for the MediaSession. This includes media button and volume events. The caller's thread will be used to post events.

Parameters
callback MediaSessionCompat.Callback: The callback object

setExtras

void setExtras (Bundle extras)

Set some extras that can be associated with the MediaSessionCompat. No assumptions should be made as to how a MediaControllerCompat 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 session.

setFlags

void setFlags (int flags)

Set any flags for the session.

Parameters
flags int: The flags to set for this session.

setMediaButtonReceiver

void setMediaButtonReceiver (PendingIntent mbr)

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 ACTION_MEDIA_BUTTON intent will be sent via the pending intent.

This method will only work on LOLLIPOP and later. Earlier platform versions must include the media button receiver in the constructor.

Parameters
mbr PendingIntent: The PendingIntent to send the media button event to.

setMetadata

void setMetadata (MediaMetadataCompat metadata)

Update the current metadata. New metadata can be created using MediaMetadata.Builder.

Parameters
metadata MediaMetadataCompat: The new metadata

setPlaybackState

void setPlaybackState (PlaybackStateCompat state)

Update the current playback state.

Parameters
state PlaybackStateCompat: The current state of playback

setPlaybackToLocal

void setPlaybackToLocal (int stream)

Set the stream this session is playing on. This will affect the system's volume handling for this session. If setPlaybackToRemote(VolumeProviderCompat) was previously called it will stop receiving volume commands and the system will begin sending volume changes to the appropriate stream.

By default sessions are on STREAM_MUSIC.

Parameters
stream int: The AudioManager stream this session is playing on.

setPlaybackToRemote

void setPlaybackToRemote (VolumeProviderCompat volumeProvider)

Configure this session to use remote volume handling. This must be called to receive volume button events, otherwise the system will adjust the current stream volume for this session. If setPlaybackToLocal(int) was previously called that stream will stop receiving volume changes for this session.

On platforms earlier than LOLLIPOP this will only allow an app to handle volume commands sent directly to the session by a MediaControllerCompat. System routing of volume keys will not use the volume provider.

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

setQueue

void setQueue (List<MediaSessionCompat.QueueItem> queue)

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 List: A list of items in the play queue.

setQueueTitle

void setQueueTitle (CharSequence title)

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.

setRatingType

void setRatingType (int type)

Set the style of rating used by this session. Apps trying to set the rating should use this style. Must be one of the following:

Parameters
type int

setSessionActivity

void setSessionActivity (PendingIntent pi)

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 startActivity(Intent).

Parameters
pi PendingIntent: The intent to launch to show UI for this Session.

Hooray!