FileDocCategorySizeDatePackage
MediaSessionCompat.javaAPI DocAndroid 5.1 API68915Thu Mar 12 22:22:56 GMT 2015android.support.v4.media.session

MediaSessionCompat

public class MediaSessionCompat extends Object
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 {@link #getSessionToken() session token} to other processes to allow them to create a {@link MediaControllerCompat} to interact with the session.

To receive commands, media keys, and other events a {@link Callback} must be set with {@link #setCallback(Callback)}.

When an app is finished performing playback it must call {@link #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 {@link android.media.session.MediaSession} introduced after API level 4 in a backwards compatible fashion.

Fields Summary
private final MediaSessionImpl
mImpl
private final MediaControllerCompat
mController
private final ArrayList
mActiveListeners
public static final int
FLAG_HANDLES_MEDIA_BUTTONS
Set this flag on the session to indicate that it can handle media button events.
public static final int
FLAG_HANDLES_TRANSPORT_CONTROLS
Set this flag on the session to indicate that it handles transport control commands through its {@link Callback}.
Constructors Summary
public MediaSessionCompat(android.content.Context context, String tag, android.content.ComponentName mediaButtonEventReceiver, android.app.PendingIntent mbrIntent)
Creates a new session.

param
context The context.
param
tag A short name for debugging purposes.
param
mediaButtonEventReceiver The component name for your receiver. This must be non-null to support platform versions earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP}.
param
mbrIntent The PendingIntent for your receiver component that handles media button events. This is optional and will be used on {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} and later instead of the component name.


                                                                                                                                  
          
              
        if (context == null) {
            throw new IllegalArgumentException("context must not be null");
        }
        if (TextUtils.isEmpty(tag)) {
            throw new IllegalArgumentException("tag must not be null or empty");
        }

        if (android.os.Build.VERSION.SDK_INT >= 21) {
            mImpl = new MediaSessionImplApi21(context, tag);
            mImpl.setMediaButtonReceiver(mbrIntent);
        } else {
            mImpl = new MediaSessionImplBase(context, tag, mediaButtonEventReceiver, mbrIntent);
        }
        mController = new MediaControllerCompat(context, this);
    
private MediaSessionCompat(android.content.Context context, MediaSessionImpl impl)

        mImpl = impl;
        mController = new MediaControllerCompat(context, this);
    
Methods Summary
public voidaddOnActiveChangeListener(android.support.v4.media.session.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.

param
listener The listener to add.

        if (listener == null) {
            throw new IllegalArgumentException("Listener may not be null");
        }
        mActiveListeners.add(listener);
    
public MediaControllerCompatgetController()
Get a controller for this session. This is a convenience method to avoid having to cache your own controller in process.

return
A controller for this session.

        return mController;
    
public java.lang.ObjectgetMediaSession()
Gets the underlying framework {@link android.media.session.MediaSession} object.

This method is only supported on API 21+.

return
The underlying {@link android.media.session.MediaSession} object, or null if none.

        return mImpl.getMediaSession();
    
public java.lang.ObjectgetRemoteControlClient()
Gets the underlying framework {@link android.media.RemoteControlClient} object.

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

return
The underlying {@link android.media.RemoteControlClient} object, or null if none.

        return mImpl.getRemoteControlClient();
    
public android.support.v4.media.session.MediaSessionCompat$TokengetSessionToken()
Retrieve a token object that can be used by apps to create a {@link MediaControllerCompat} for interacting with this session. The owner of the session is responsible for deciding how to distribute these tokens.

On platform versions before {@link android.os.Build.VERSION_CODES#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.

return
A token that can be used to create a media controller for this session.

        return mImpl.getSessionToken();
    
public booleanisActive()
Get the current active state of this session.

return
True if the session is active, false otherwise.

        return mImpl.isActive();
    
public static android.support.v4.media.session.MediaSessionCompatobtain(android.content.Context context, java.lang.Object mediaSession)
Obtain a compat wrapper for an existing MediaSession.

param
mediaSession The {@link android.media.session.MediaSession} to wrap.
return
A compat wrapper for the provided session.

        return new MediaSessionCompat(context, new MediaSessionImplApi21(mediaSession));
    
public voidrelease()
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.

        mImpl.release();
    
public voidremoveOnActiveChangeListener(android.support.v4.media.session.MediaSessionCompat$OnActiveChangeListener listener)
Stops the listener from being notified when the active status of this session changes.

param
listener The listener to remove.

        if (listener == null) {
            throw new IllegalArgumentException("Listener may not be null");
        }
        mActiveListeners.remove(listener);
    
public voidsendSessionEvent(java.lang.String event, android.os.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.

param
event The name of the event to send
param
extras Any extras included with the event

        if (TextUtils.isEmpty(event)) {
            throw new IllegalArgumentException("event cannot be null or empty");
        }
        mImpl.sendSessionEvent(event, extras);
    
public voidsetActive(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 {@link android.os.Build.VERSION_CODES#LOLLIPOP}, {@link #setMediaButtonReceiver(PendingIntent)} must be called before setting this to true.

param
active Whether this session is active or not.

        mImpl.setActive(active);
        for (OnActiveChangeListener listener : mActiveListeners) {
            listener.onActiveChanged();
        }
    
public voidsetCallback(android.support.v4.media.session.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.

param
callback The callback object

        setCallback(callback, null);
    
public voidsetCallback(android.support.v4.media.session.MediaSessionCompat$Callback callback, android.os.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.

param
callback The callback to receive updates on.
param
handler The handler that events should be posted on.

        mImpl.setCallback(callback, handler != null ? handler : new Handler());
    
public voidsetExtras(android.os.Bundle extras)
Set some extras that can be associated with the {@link MediaSessionCompat}. No assumptions should be made as to how a {@link MediaControllerCompat} will handle these extras. Keys should be fully qualified (e.g. com.example.MY_EXTRA) to avoid conflicts.

param
extras The extras associated with the session.

        mImpl.setExtras(extras);
    
public voidsetFlags(int flags)
Set any flags for the session.

param
flags The flags to set for this session.

        mImpl.setFlags(flags);
    
public voidsetMediaButtonReceiver(android.app.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 {@link Intent#ACTION_MEDIA_BUTTON} intent will be sent via the pending intent.

This method will only work on {@link android.os.Build.VERSION_CODES#LOLLIPOP} and later. Earlier platform versions must include the media button receiver in the constructor.

param
mbr The {@link PendingIntent} to send the media button event to.

        mImpl.setMediaButtonReceiver(mbr);
    
public voidsetMetadata(android.support.v4.media.MediaMetadataCompat metadata)
Update the current metadata. New metadata can be created using {@link android.media.MediaMetadata.Builder}.

param
metadata The new metadata

        mImpl.setMetadata(metadata);
    
public voidsetPlaybackState(PlaybackStateCompat state)
Update the current playback state.

param
state The current state of playback

        mImpl.setPlaybackState(state);
    
public voidsetPlaybackToLocal(int stream)
Set the stream this session is playing on. This will affect the system's volume handling for this session. If {@link #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 {@link AudioManager#STREAM_MUSIC}.

param
stream The {@link AudioManager} stream this session is playing on.

        mImpl.setPlaybackToLocal(stream);
    
public voidsetPlaybackToRemote(android.support.v4.media.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 {@link #setPlaybackToLocal} was previously called that stream will stop receiving volume changes for this session.

On platforms earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP} this will only allow an app to handle volume commands sent directly to the session by a {@link MediaControllerCompat}. System routing of volume keys will not use the volume provider.

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

        if (volumeProvider == null) {
            throw new IllegalArgumentException("volumeProvider may not be null!");
        }
        mImpl.setPlaybackToRemote(volumeProvider);
    
public voidsetQueue(java.util.List 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.

param
queue A list of items in the play queue.

        mImpl.setQueue(queue);
    
public voidsetQueueTitle(java.lang.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.

param
title The title of the play queue.

        mImpl.setQueueTitle(title);
    
public voidsetRatingType(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:
  • {@link RatingCompat#RATING_NONE}
  • {@link RatingCompat#RATING_3_STARS}
  • {@link RatingCompat#RATING_4_STARS}
  • {@link RatingCompat#RATING_5_STARS}
  • {@link RatingCompat#RATING_HEART}
  • {@link RatingCompat#RATING_PERCENTAGE}
  • {@link RatingCompat#RATING_THUMB_UP_DOWN}

        mImpl.setRatingType(type);
    
public voidsetSessionActivity(android.app.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 {@link Activity#startActivity(Intent)}.

param
pi The intent to launch to show UI for this Session.

        mImpl.setSessionActivity(pi);