MediaSessionCompat


public class 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 Callback must be set with setCallback.

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 android.media.session.MediaSession introduced after API level 4 in a backwards compatible fashion.

Summary

Nested types

public abstract class MediaSessionCompat.Callback

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

public final class MediaSessionCompat.QueueItem implements Parcelable

A single item that is part of the play queue.

public final class MediaSessionCompat.Token implements Parcelable

Represents an ongoing session.

Constants

static final String
ACTION_FLAG_AS_INAPPROPRIATE = "android.support.v4.media.session.action.FLAG_AS_INAPPROPRIATE"

Predefined custom action to flag the media that is currently playing as inappropriate.

static final String
ACTION_FOLLOW = "android.support.v4.media.session.action.FOLLOW"

Predefined custom action to follow an artist, album, or playlist.

static final String
ACTION_SKIP_AD = "android.support.v4.media.session.action.SKIP_AD"

Predefined custom action to skip the advertisement that is currently playing.

static final String
ACTION_UNFOLLOW = "android.support.v4.media.session.action.UNFOLLOW"

Predefined custom action to unfollow an artist, album, or playlist.

static final String
ARGUMENT_MEDIA_ATTRIBUTE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE"

Argument to indicate the media attribute.

static final String
ARGUMENT_MEDIA_ATTRIBUTE_VALUE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE_VALUE"

String argument to indicate the value of the media attribute (e.g., the name of the artist).

static final int

This field is deprecated.

This flag is no longer used.

static final int

Sets this flag on the session to indicate that it handles queue management commands through its Callback.

static final int

This field is deprecated.

This flag is no longer used.

static final int

The value of ARGUMENT_MEDIA_ATTRIBUTE indicating the album.

static final int

The value of ARGUMENT_MEDIA_ATTRIBUTE indicating the artist.

static final int

The value of ARGUMENT_MEDIA_ATTRIBUTE indicating the playlist.

Public constructors

Creates a new session.

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

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

MediaSessionCompat(
    @NonNull Context context,
    @NonNull String tag,
    @Nullable ComponentName mbrComponent,
    @Nullable PendingIntent mbrIntent,
    @Nullable Bundle sessionInfo
)

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

Public methods

void

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

static MediaSessionCompat
fromMediaSession(Context context, Object mediaSession)

Creates an instance from a framework android.media.session.MediaSession object.

MediaControllerCompat

Gets a controller for this session.

final @NonNull MediaSessionManager.RemoteUserInfo

Gets the controller information who sent the current request.

Object

Gets the underlying framework android.media.session.MediaSession object.

Object

Gets the underlying framework android.media.RemoteControlClient object.

MediaSessionCompat.Token

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

boolean

Gets the current active state of this session.

void

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

void

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

void
sendSessionEvent(String event, Bundle extras)

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

void
setActive(boolean active)

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

void

Adds a callback to receive updates on for the MediaSession.

void

Sets the callback to receive updates for the MediaSession.

void
setCaptioningEnabled(boolean enabled)

Enables/disables captioning for this session.

void
setExtras(Bundle extras)

Sets some extras that can be associated with the MediaSessionCompat.

void
setFlags(int flags)

Sets any flags for the session.

void

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

void

Updates the current metadata.

void

Updates the current playback state.

void
setPlaybackToLocal(int stream)

Sets the stream this session is playing on.

void

Configures this session to use remote volume handling.

void

Updates the list of items in the play queue.

void

Sets the title of the play queue.

void
setRatingType(int type)

Sets the style of rating used by this session.

void
setRepeatMode(int repeatMode)

Sets the repeat mode for this session.

void

Sets an intent for launching UI for this Session.

void
setShuffleMode(int shuffleMode)

Sets the shuffle mode for this session.

Constants

ACTION_FLAG_AS_INAPPROPRIATE

Added in 1.1.0
public static final String ACTION_FLAG_AS_INAPPROPRIATE = "android.support.v4.media.session.action.FLAG_AS_INAPPROPRIATE"

Predefined custom action to flag the media that is currently playing as inappropriate.

See also
onCustomAction

ACTION_FOLLOW

Added in 1.1.0
public static final String ACTION_FOLLOW = "android.support.v4.media.session.action.FOLLOW"

Predefined custom action to follow an artist, album, or playlist. The extra bundle must have ARGUMENT_MEDIA_ATTRIBUTE to indicate the type of the follow action. The bundle can also have an optional string argument, ARGUMENT_MEDIA_ATTRIBUTE_VALUE, to specify the target to follow (e.g., the name of the artist to follow). If this argument is omitted, the currently playing media will be the target of the action. Thus, the session must perform the follow action with the current metadata. If there's no specified attribute in the current metadata, the controller must not omit this argument.

ACTION_SKIP_AD

Added in 1.1.0
public static final String ACTION_SKIP_AD = "android.support.v4.media.session.action.SKIP_AD"

Predefined custom action to skip the advertisement that is currently playing.

See also
onCustomAction

ACTION_UNFOLLOW

Added in 1.1.0
public static final String ACTION_UNFOLLOW = "android.support.v4.media.session.action.UNFOLLOW"

Predefined custom action to unfollow an artist, album, or playlist. The extra bundle must have ARGUMENT_MEDIA_ATTRIBUTE to indicate the type of the unfollow action. The bundle can also have an optional string argument, ARGUMENT_MEDIA_ATTRIBUTE_VALUE, to specify the target to unfollow (e.g., the name of the artist to unfollow). If this argument is omitted, the currently playing media will be the target of the action. Thus, the session must perform the unfollow action with the current metadata. If there's no specified attribute in the current metadata, the controller must not omit this argument.

ARGUMENT_MEDIA_ATTRIBUTE

Added in 1.1.0
public static final String ARGUMENT_MEDIA_ATTRIBUTE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE"

Argument to indicate the media attribute. It should be one of the following:

ARGUMENT_MEDIA_ATTRIBUTE_VALUE

Added in 1.1.0
public static final String ARGUMENT_MEDIA_ATTRIBUTE_VALUE = "android.support.v4.media.session.ARGUMENT_MEDIA_ATTRIBUTE_VALUE"

String argument to indicate the value of the media attribute (e.g., the name of the artist).

FLAG_HANDLES_MEDIA_BUTTONS

Added in 1.1.0
Deprecated in 1.1.0
public static final int FLAG_HANDLES_MEDIA_BUTTONS = 1

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

FLAG_HANDLES_QUEUE_COMMANDS

Added in 1.1.0
public static final int FLAG_HANDLES_QUEUE_COMMANDS = 4

Sets this flag on the session to indicate that it handles queue management commands through its Callback.

FLAG_HANDLES_TRANSPORT_CONTROLS

Added in 1.1.0
Deprecated in 1.1.0
public static final int FLAG_HANDLES_TRANSPORT_CONTROLS = 2

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

MEDIA_ATTRIBUTE_ALBUM

Added in 1.1.0
public static final int MEDIA_ATTRIBUTE_ALBUM = 1

The value of ARGUMENT_MEDIA_ATTRIBUTE indicating the album.

MEDIA_ATTRIBUTE_ARTIST

Added in 1.1.0
public static final int MEDIA_ATTRIBUTE_ARTIST = 0

The value of ARGUMENT_MEDIA_ATTRIBUTE indicating the artist.

MEDIA_ATTRIBUTE_PLAYLIST

Added in 1.1.0
public static final int MEDIA_ATTRIBUTE_PLAYLIST = 2

The value of ARGUMENT_MEDIA_ATTRIBUTE indicating the playlist.

Public constructors

MediaSessionCompat

Added in 1.1.0
public MediaSessionCompat(@NonNull Context context, @NonNull 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
@NonNull Context context

The context to use to create the session.

@NonNull String tag

A short name for debugging purposes.

MediaSessionCompat

Added in 1.1.0
public MediaSessionCompat(
    @NonNull Context context,
    @NonNull String tag,
    @Nullable ComponentName mbrComponent,
    @Nullable 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.

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 if it's not specified. See MediaButtonReceiver for more details.

Parameters
@NonNull Context context

The context to use to create the session.

@NonNull String tag

A short name for debugging purposes.

@Nullable ComponentName mbrComponent

The component name for your media button receiver.

@Nullable PendingIntent mbrIntent

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.

MediaSessionCompat

Added in 1.2.0
public MediaSessionCompat(
    @NonNull Context context,
    @NonNull String tag,
    @Nullable ComponentName mbrComponent,
    @Nullable PendingIntent mbrIntent,
    @Nullable Bundle sessionInfo
)

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.

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 if it's not specified. See MediaButtonReceiver for more details.

The sessionInfo can include additional unchanging information about this session. For example, it can include the version of the application, or other app-specific unchanging information.
Parameters
@NonNull Context context

The context to use to create the session.

@NonNull String tag

A short name for debugging purposes.

@Nullable ComponentName mbrComponent

The component name for your media button receiver.

@Nullable PendingIntent mbrIntent

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.

@Nullable Bundle sessionInfo

A bundle for additional information about this session, or EMPTY if none. Controllers can get this information by calling getSessionInfo. An IllegalArgumentException will be thrown if this contains any non-framework Parcelable objects.

Public methods

addOnActiveChangeListener

Added in 1.1.0
public 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
MediaSessionCompat.OnActiveChangeListener listener

The listener to add.

fromMediaSession

Added in 1.1.0
public static MediaSessionCompat fromMediaSession(Context context, Object mediaSession)

Creates an instance from a framework android.media.session.MediaSession object.

This method is only supported on API 21+. On API 20 and below, it returns null.

Note: A MediaSessionCompat object returned from this method may not provide the full functionality of MediaSessionCompat until setting a new MediaSessionCompat.Callback. To avoid this, when both a MediaSessionCompat and a framework android.media.session.MediaSession are needed, it is recommended to create a MediaSessionCompat first and get the framework session through getMediaSession.

Parameters
Context context

The context to use to create the session.

Object mediaSession

A android.media.session.MediaSession object.

Returns
MediaSessionCompat

An equivalent MediaSessionCompat object, or null if none.

getController

Added in 1.1.0
public MediaControllerCompat getController()

Gets 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.

getCurrentControllerInfo

Added in 1.1.0
public final @NonNull MediaSessionManager.RemoteUserInfo getCurrentControllerInfo()

Gets the controller information who sent the current request.

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

Note: From API 21 to 23, this method returns a fake RemoteUserInfo which has following values:

Note: From API 24 to 27, the RemoteUserInfo returned from this method will have negative uid and pid. Most of the cases it will have the correct package name, but sometimes it will fail to get the right one.

getMediaSession

Added in 1.1.0
public Object getMediaSession()

Gets the underlying framework android.media.session.MediaSession object.

This method is only supported on API 21+.

Returns
Object

The underlying android.media.session.MediaSession object, or null if none.

getRemoteControlClient

Added in 1.1.0
public Object getRemoteControlClient()

Gets the underlying framework android.media.RemoteControlClient object.

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

Returns
Object

The underlying android.media.RemoteControlClient object, or null if none.

getSessionToken

Added in 1.1.0
public MediaSessionCompat.Token getSessionToken()

Retrieves 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

Added in 1.1.0
public boolean isActive()

Gets the current active state of this session.

Returns
boolean

True if the session is active, false otherwise.

release

Added in 1.1.0
public 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

Added in 1.1.0
public void removeOnActiveChangeListener(
    MediaSessionCompat.OnActiveChangeListener listener
)

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

Parameters
MediaSessionCompat.OnActiveChangeListener listener

The listener to remove.

sendSessionEvent

Added in 1.1.0
public void sendSessionEvent(String event, Bundle extras)

Sends 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
String event

The name of the event to send

Bundle extras

Any extras included with the event

setActive

Added in 1.1.0
public void setActive(boolean active)

Sets 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
boolean active

Whether this session is active or not.

setCallback

Added in 1.1.0
public void setCallback(MediaSessionCompat.Callback callback)

Adds 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. Set the callback to null to stop receiving events.

Don't reuse the callback among the sessions. Callbacks keep internal reference to the session when it's set, so it may misbehave.

Parameters
MediaSessionCompat.Callback callback

The callback object

setCallback

Added in 1.1.0
public void setCallback(MediaSessionCompat.Callback callback, Handler handler)

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

Don't reuse the callback among the sessions. Callbacks keep internal reference to the session when it's set, so it may misbehave.

Parameters
MediaSessionCompat.Callback callback

The callback to receive updates on.

Handler handler

The handler that events should be posted on.

setCaptioningEnabled

Added in 1.1.0
public void setCaptioningEnabled(boolean enabled)

Enables/disables captioning for this session.

Parameters
boolean enabled

true to enable captioning, false to disable.

setExtras

Added in 1.1.0
public void setExtras(Bundle extras)

Sets 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
Bundle extras

The extras associated with the session.

setFlags

Added in 1.1.0
public void setFlags(int flags)

Sets any flags for the session.

Parameters
int flags

The flags to set for this session.

setMediaButtonReceiver

Added in 1.1.0
public void setMediaButtonReceiver(PendingIntent mbr)

Sets 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
PendingIntent mbr

The PendingIntent to send the media button event to.

setMetadata

Added in 1.1.0
public void setMetadata(MediaMetadataCompat metadata)

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

Parameters
MediaMetadataCompat metadata

The new metadata

See also
putBitmap

setPlaybackState

Added in 1.1.0
public void setPlaybackState(PlaybackStateCompat state)

Updates the current playback state.

Parameters
PlaybackStateCompat state

The current state of playback

setPlaybackToLocal

Added in 1.1.0
public void setPlaybackToLocal(int stream)

Sets the stream this session is playing on. 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 are on STREAM_MUSIC.

Parameters
int stream

The AudioManager stream this session is playing on.

setPlaybackToRemote

Added in 1.1.0
public void setPlaybackToRemote(VolumeProviderCompat volumeProvider)

Configures 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 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
VolumeProviderCompat volumeProvider

The provider that will handle volume changes. May not be null.

setQueue

Added in 1.1.0
public void setQueue(List<MediaSessionCompat.QueueItem> queue)

Updates 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. The id of each item should be unique within the play queue. 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
List<MediaSessionCompat.QueueItem> queue

A list of items in the play queue.

setQueueTitle

Added in 1.1.0
public void setQueueTitle(CharSequence title)

Sets 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
CharSequence title

The title of the play queue.

setRatingType

Added in 1.1.0
public void setRatingType(int type)

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

setRepeatMode

Added in 1.1.0
public void setRepeatMode(int repeatMode)

Sets the repeat mode for this session.

Note that if this method is not called before, getRepeatMode will return REPEAT_MODE_NONE.

Parameters
int repeatMode

The repeat mode. Must be one of the followings: REPEAT_MODE_NONE, REPEAT_MODE_ONE, REPEAT_MODE_ALL, REPEAT_MODE_GROUP

setSessionActivity

Added in 1.1.0
public void setSessionActivity(PendingIntent pi)

Sets 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.

Parameters
PendingIntent pi

The intent to launch to show UI for this Session.

setShuffleMode

Added in 1.1.0
public void setShuffleMode(int shuffleMode)

Sets the shuffle mode for this session.

Note that if this method is not called before, getShuffleMode will return SHUFFLE_MODE_NONE.

Parameters
int shuffleMode

The shuffle mode. Must be one of the followings: SHUFFLE_MODE_NONE, SHUFFLE_MODE_ALL, SHUFFLE_MODE_GROUP