FileDocCategorySizeDatePackage
MediaController.javaAPI DocAndroid 5.1 API33807Thu Mar 12 22:22:30 GMT 2015android.media.session

MediaController

public final class MediaController extends Object
Allows an app to interact with an ongoing media session. Media buttons and other commands can be sent to the session. A callback may be registered to receive updates from the session, such as metadata and play state changes.

A MediaController can be created through {@link MediaSessionManager} if you hold the "android.permission.MEDIA_CONTENT_CONTROL" permission or are an enabled notification listener or by getting a {@link MediaSession.Token} directly from the session owner.

MediaController objects are thread-safe.

Fields Summary
private static final String
TAG
private static final int
MSG_EVENT
private static final int
MSG_UPDATE_PLAYBACK_STATE
private static final int
MSG_UPDATE_METADATA
private static final int
MSG_UPDATE_VOLUME
private static final int
MSG_UPDATE_QUEUE
private static final int
MSG_UPDATE_QUEUE_TITLE
private static final int
MSG_UPDATE_EXTRAS
private static final int
MSG_DESTROYED
private final ISessionController
mSessionBinder
private final MediaSession.Token
mToken
private final android.content.Context
mContext
private final CallbackStub
mCbStub
private final ArrayList
mCallbacks
private final Object
mLock
private boolean
mCbRegistered
private String
mPackageName
private String
mTag
private final TransportControls
mTransportControls
Constructors Summary
public MediaController(android.content.Context context, ISessionController sessionBinder)
Call for creating a MediaController directly from a binder. Should only be used by framework code.

hide


                          
         
        if (sessionBinder == null) {
            throw new IllegalArgumentException("Session token cannot be null");
        }
        if (context == null) {
            throw new IllegalArgumentException("Context cannot be null");
        }
        mSessionBinder = sessionBinder;
        mTransportControls = new TransportControls();
        mToken = new MediaSession.Token(sessionBinder);
        mContext = context;
    
public MediaController(android.content.Context context, MediaSession.Token token)
Create a new MediaController from a session's token.

param
context The caller's context.
param
token The token for the session.

        this(context, token.getBinder());
    
Methods Summary
private voidaddCallbackLocked(android.media.session.MediaController$Callback cb, android.os.Handler handler)

        if (getHandlerForCallbackLocked(cb) != null) {
            Log.w(TAG, "Callback is already added, ignoring");
            return;
        }
        MessageHandler holder = new MessageHandler(handler.getLooper(), cb);
        mCallbacks.add(holder);
        holder.mRegistered = true;

        if (!mCbRegistered) {
            try {
                mSessionBinder.registerCallbackListener(mCbStub);
                mCbRegistered = true;
            } catch (RemoteException e) {
                Log.e(TAG, "Dead object in registerCallback", e);
            }
        }
    
public voidadjustVolume(int direction, int flags)
Adjust the volume of the output this session is playing on. The direction must be one of {@link AudioManager#ADJUST_LOWER}, {@link AudioManager#ADJUST_RAISE}, or {@link AudioManager#ADJUST_SAME}. The command will be ignored if the session does not support {@link VolumeProvider#VOLUME_CONTROL_RELATIVE} or {@link VolumeProvider#VOLUME_CONTROL_ABSOLUTE}. The flags in {@link AudioManager} may be used to affect the handling.

see
#getPlaybackInfo()
param
direction The direction to adjust the volume in.
param
flags Any flags to pass with the command.

        try {
            mSessionBinder.adjustVolume(direction, flags, mContext.getPackageName());
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling adjustVolumeBy.", e);
        }
    
public booleancontrolsSameSession(android.media.session.MediaController other)

hide

        if (other == null) return false;
        return mSessionBinder.asBinder() == other.getSessionBinder().asBinder();
    
public booleandispatchMediaButtonEvent(android.view.KeyEvent keyEvent)
Send the specified media button event to the session. Only media keys can be sent by this method, other keys will be ignored.

param
keyEvent The media button event to dispatch.
return
true if the event was sent to the session, false otherwise.

        if (keyEvent == null) {
            throw new IllegalArgumentException("KeyEvent may not be null");
        }
        if (!KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
            return false;
        }
        try {
            return mSessionBinder.sendMediaButton(keyEvent);
        } catch (RemoteException e) {
            // System is dead. =(
        }
        return false;
    
public android.os.BundlegetExtras()
Get the extras for this session.

        try {
            return mSessionBinder.getExtras();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getExtras", e);
        }
        return null;
    
public longgetFlags()
Get the flags for this session. Flags are defined in {@link MediaSession}.

return
The current set of flags for the session.

        try {
            return mSessionBinder.getFlags();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getFlags.", e);
        }
        return 0;
    
private android.media.session.MediaController$MessageHandlergetHandlerForCallbackLocked(android.media.session.MediaController$Callback cb)

        if (cb == null) {
            throw new IllegalArgumentException("Callback cannot be null");
        }
        for (int i = mCallbacks.size() - 1; i >= 0; i--) {
            MessageHandler handler = mCallbacks.get(i);
            if (cb == handler.mCallback) {
                return handler;
            }
        }
        return null;
    
public android.media.MediaMetadatagetMetadata()
Get the current metadata for this session.

return
The current MediaMetadata or null.

        try {
            return mSessionBinder.getMetadata();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getMetadata.", e);
            return null;
        }
    
public java.lang.StringgetPackageName()
Get the session owner's package name.

return
The package name of of the session owner.

        if (mPackageName == null) {
            try {
                mPackageName = mSessionBinder.getPackageName();
            } catch (RemoteException e) {
                Log.d(TAG, "Dead object in getPackageName.", e);
            }
        }
        return mPackageName;
    
public android.media.session.MediaController$PlaybackInfogetPlaybackInfo()
Get the current playback info for this session.

return
The current playback info or null.

        try {
            ParcelableVolumeInfo result = mSessionBinder.getVolumeAttributes();
            return new PlaybackInfo(result.volumeType, result.audioAttrs, result.controlType,
                    result.maxVolume, result.currentVolume);

        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getAudioInfo.", e);
        }
        return null;
    
public PlaybackStategetPlaybackState()
Get the current playback state for this session.

return
The current PlaybackState or null

        try {
            return mSessionBinder.getPlaybackState();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getPlaybackState.", e);
            return null;
        }
    
public java.util.ListgetQueue()
Get the current play queue for this session if one is set. If you only care about the current item {@link #getMetadata()} should be used.

return
The current play queue or null.

        try {
            ParceledListSlice queue = mSessionBinder.getQueue();
            if (queue != null) {
                return queue.getList();
            }
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getQueue.", e);
        }
        return null;
    
public java.lang.CharSequencegetQueueTitle()
Get the queue title for this session.

        try {
            return mSessionBinder.getQueueTitle();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getQueueTitle", e);
        }
        return null;
    
public intgetRatingType()
Get the rating type supported by the session. One of:
  • {@link Rating#RATING_NONE}
  • {@link Rating#RATING_HEART}
  • {@link Rating#RATING_THUMB_UP_DOWN}
  • {@link Rating#RATING_3_STARS}
  • {@link Rating#RATING_4_STARS}
  • {@link Rating#RATING_5_STARS}
  • {@link Rating#RATING_PERCENTAGE}

return
The supported rating type

        try {
            return mSessionBinder.getRatingType();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getRatingType.", e);
            return Rating.RATING_NONE;
        }
    
public android.app.PendingIntentgetSessionActivity()
Get an intent for launching UI associated with this session if one exists.

return
A {@link PendingIntent} to launch UI or null.

        try {
            return mSessionBinder.getLaunchPendingIntent();
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling getPendingIntent.", e);
        }
        return null;
    
ISessionControllergetSessionBinder()

        return mSessionBinder;
    
public MediaSession.TokengetSessionToken()
Get the token for the session this is connected to.

return
The token for the connected session.

        return mToken;
    
public java.lang.StringgetTag()
Get the session's tag for debugging purposes.

return
The session's tag.
hide

        if (mTag == null) {
            try {
                mTag = mSessionBinder.getTag();
            } catch (RemoteException e) {
                Log.d(TAG, "Dead object in getTag.", e);
            }
        }
        return mTag;
    
public android.media.session.MediaController$TransportControlsgetTransportControls()
Get a {@link TransportControls} instance to send transport actions to the associated session.

return
A transport controls instance.

        return mTransportControls;
    
private final voidpostMessage(int what, java.lang.Object obj, android.os.Bundle data)

        synchronized (mLock) {
            for (int i = mCallbacks.size() - 1; i >= 0; i--) {
                mCallbacks.get(i).post(what, obj, data);
            }
        }
    
public voidregisterCallback(android.media.session.MediaController$Callback callback)
Registers a callback to receive updates from the Session. Updates will be posted on the caller's thread.

param
callback The callback object, must not be null.

        registerCallback(callback, null);
    
public voidregisterCallback(android.media.session.MediaController$Callback callback, android.os.Handler handler)
Registers a callback to receive updates from the session. Updates will be posted on the specified handler's thread.

param
callback The callback object, must not be null.
param
handler The handler to post updates on. If null the callers thread will be used.

        if (callback == null) {
            throw new IllegalArgumentException("callback must not be null");
        }
        if (handler == null) {
            handler = new Handler();
        }
        synchronized (mLock) {
            addCallbackLocked(callback, handler);
        }
    
private booleanremoveCallbackLocked(android.media.session.MediaController$Callback cb)

        boolean success = false;
        for (int i = mCallbacks.size() - 1; i >= 0; i--) {
            MessageHandler handler = mCallbacks.get(i);
            if (cb == handler.mCallback) {
                mCallbacks.remove(i);
                success = true;
                handler.mRegistered = false;
            }
        }
        if (mCbRegistered && mCallbacks.size() == 0) {
            try {
                mSessionBinder.unregisterCallbackListener(mCbStub);
            } catch (RemoteException e) {
                Log.e(TAG, "Dead object in removeCallbackLocked");
            }
            mCbRegistered = false;
        }
        return success;
    
public voidsendCommand(java.lang.String command, android.os.Bundle args, android.os.ResultReceiver cb)
Sends a generic command to the session. It is up to the session creator to decide what commands and parameters they will support. As such, commands should only be sent to sessions that the controller owns.

param
command The command to send
param
args Any parameters to include with the command
param
cb The callback to receive the result on

        if (TextUtils.isEmpty(command)) {
            throw new IllegalArgumentException("command cannot be null or empty");
        }
        try {
            mSessionBinder.sendCommand(command, args, cb);
        } catch (RemoteException e) {
            Log.d(TAG, "Dead object in sendCommand.", e);
        }
    
public voidsetVolumeTo(int value, int flags)
Set the volume of the output this session is playing on. The command will be ignored if it does not support {@link VolumeProvider#VOLUME_CONTROL_ABSOLUTE}. The flags in {@link AudioManager} may be used to affect the handling.

see
#getPlaybackInfo()
param
value The value to set it to, between 0 and the reported max.
param
flags Flags from {@link AudioManager} to include with the volume request.

        try {
            mSessionBinder.setVolumeTo(value, flags, mContext.getPackageName());
        } catch (RemoteException e) {
            Log.wtf(TAG, "Error calling setVolumeTo.", e);
        }
    
public voidunregisterCallback(android.media.session.MediaController$Callback callback)
Unregisters the specified callback. If an update has already been posted you may still receive it after calling this method.

param
callback The callback to remove.

        if (callback == null) {
            throw new IllegalArgumentException("callback must not be null");
        }
        synchronized (mLock) {
            removeCallbackLocked(callback);
        }