FileDocCategorySizeDatePackage
RemoteController.javaAPI DocAndroid 5.1 API45085Thu Mar 12 22:22:30 GMT 2015android.media

RemoteController

public final class RemoteController extends Object
The RemoteController class is used to control media playback, display and update media metadata and playback status, published by applications using the {@link RemoteControlClient} class.

A RemoteController shall be registered through {@link AudioManager#registerRemoteController(RemoteController)} in order for the system to send media event updates to the {@link OnClientUpdateListener} listener set in the class constructor. Implement the methods of the interface to receive the information published by the active {@link RemoteControlClient} instances.
By default an {@link OnClientUpdateListener} implementation will not receive bitmaps for album art. Use {@link #setArtworkConfiguration(int, int)} to receive images as well.

Registration requires the {@link OnClientUpdateListener} listener to be one of the enabled notification listeners (see {@link android.service.notification.NotificationListenerService}).

deprecated
Use {@link MediaController} instead.

Fields Summary
private static final int
MAX_BITMAP_DIMENSION
private static final int
TRANSPORT_UNKNOWN
private static final String
TAG
private static final boolean
DEBUG
private static final boolean
USE_SESSIONS
private static final Object
mGenLock
private static final Object
mInfoLock
private final RcDisplay
mRcd
private final android.content.Context
mContext
private final AudioManager
mAudioManager
private final int
mMaxBitmapDimension
private MetadataEditor
mMetadataEditor
private android.media.session.MediaSessionManager
mSessionManager
private MediaSessionManager.OnActiveSessionsChangedListener
mSessionListener
private MediaController.Callback
mSessionCb
private int
mClientGenerationIdCurrent
Synchronized on mGenLock
private boolean
mIsRegistered
Synchronized on mInfoLock
private android.app.PendingIntent
mClientPendingIntentCurrent
private OnClientUpdateListener
mOnClientUpdateListener
private PlaybackInfo
mLastPlaybackInfo
private int
mArtworkWidth
private int
mArtworkHeight
private boolean
mEnabled
private android.media.session.MediaController
mCurrentSession
public static final int
POSITION_SYNCHRONIZATION_NONE
Default playback position synchronization mode where the RemoteControlClient is not asked regularly for its playback position to see if it has drifted from the estimated position.
public static final int
POSITION_SYNCHRONIZATION_CHECK
The playback position synchronization mode where the RemoteControlClient instances which expose their playback position to the framework, will be regularly polled to check whether any drift has been noticed between their estimated position and the one they report. Note that this mode should only ever be used when needing to display very accurate playback position, as regularly polling a RemoteControlClient for its position may have an impact on battery life (if applicable) when this query will trigger network transactions in the case of remote playback.
private final EventHandler
mEventHandler
private static final int
MSG_NEW_PENDING_INTENT
private static final int
MSG_NEW_PLAYBACK_INFO
private static final int
MSG_NEW_TRANSPORT_INFO
private static final int
MSG_NEW_METADATA
private static final int
MSG_CLIENT_CHANGE
private static final int
MSG_DISPLAY_ENABLE
private static final int
MSG_NEW_PLAYBACK_STATE
private static final int
MSG_NEW_MEDIA_METADATA
private static final int
SENDMSG_REPLACE
If the msg is already queued, replace it with this one.
private static final int
SENDMSG_NOOP
If the msg is already queued, ignore this one and leave the old.
private static final int
SENDMSG_QUEUE
If the msg is already queued, queue this one and leave the old.
Constructors Summary
public RemoteController(android.content.Context context, OnClientUpdateListener updateListener)
Class constructor.

param
context the {@link Context}, must be non-null.
param
updateListener the listener to be called whenever new client information is available, must be non-null.
throws
IllegalArgumentException


                                         
        
              
        this(context, updateListener, null);
    
public RemoteController(android.content.Context context, OnClientUpdateListener updateListener, android.os.Looper looper)
Class constructor.

param
context the {@link Context}, must be non-null.
param
updateListener the listener to be called whenever new client information is available, must be non-null.
param
looper the {@link Looper} on which to run the event loop, or null to use the current thread's looper.
throws
java.lang.IllegalArgumentException

        if (context == null) {
            throw new IllegalArgumentException("Invalid null Context");
        }
        if (updateListener == null) {
            throw new IllegalArgumentException("Invalid null OnClientUpdateListener");
        }
        if (looper != null) {
            mEventHandler = new EventHandler(this, looper);
        } else {
            Looper l = Looper.myLooper();
            if (l != null) {
                mEventHandler = new EventHandler(this, l);
            } else {
                throw new IllegalArgumentException("Calling thread not associated with a looper");
            }
        }
        mOnClientUpdateListener = updateListener;
        mContext = context;
        mRcd = new RcDisplay(this);
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mSessionManager = (MediaSessionManager) context
                .getSystemService(Context.MEDIA_SESSION_SERVICE);
        mSessionListener = new TopTransportSessionListener();

        if (ActivityManager.isLowRamDeviceStatic()) {
            mMaxBitmapDimension = MAX_BITMAP_DIMENSION;
        } else {
            final DisplayMetrics dm = context.getResources().getDisplayMetrics();
            mMaxBitmapDimension = Math.max(dm.widthPixels, dm.heightPixels);
        }
    
Methods Summary
public booleanclearArtworkConfiguration()
Prevents this RemoteController from receiving artwork images.

return
true if receiving artwork images was successfully disabled.

        return setArtworkConfiguration(false, -1, -1);
    
public android.media.RemoteController$MetadataEditoreditMetadata()
Creates a {@link MetadataEditor} for updating metadata values of the editable keys of the current {@link RemoteControlClient}. This method can only be called on a registered RemoteController.

return
a new MetadataEditor instance.

        MetadataEditor editor = new MetadataEditor();
        editor.mEditorMetadata = new Bundle();
        editor.mEditorArtwork = null;
        editor.mMetadataChanged = true;
        editor.mArtworkChanged = true;
        editor.mEditableKeys = 0;
        return editor;
    
int[]getArtworkSize()

hide
Used by AudioManager to read the current artwork dimension
return
array containing width (index 0) and height (index 1) of currently set artwork size

        synchronized (mInfoLock) {
            int[] size = { mArtworkWidth, mArtworkHeight };
            return size;
        }
    
public longgetEstimatedMediaPosition()
Return the estimated playback position of the current media track or a negative value if not available.

The value returned is estimated by the current process and may not be perfect. The time returned by this method is calculated from the last state change time based on the current play position at that time and the last known playback speed. An application may call {@link #setSynchronizationMode(int)} to apply a synchronization policy that will periodically re-sync the estimated position with the RemoteControlClient.

return
the current estimated playback position in milliseconds or a negative value if not available
see
OnClientUpdateListener#onClientPlaybackStateUpdate(int, long, long, float)

        if (USE_SESSIONS) {
            synchronized (mInfoLock) {
                if (mCurrentSession != null) {
                    PlaybackState state = mCurrentSession.getPlaybackState();
                    if (state != null) {
                        return state.getPosition();
                    }
                }
            }
        } else {
            final PlaybackInfo lastPlaybackInfo;
            synchronized (mInfoLock) {
                lastPlaybackInfo = mLastPlaybackInfo;
            }
            if (lastPlaybackInfo != null) {
                if (!RemoteControlClient.playbackPositionShouldMove(lastPlaybackInfo.mState)) {
                    return lastPlaybackInfo.mCurrentPosMs;
                }

                // Take the current position at the time of state change and
                // estimate.
                final long thenPos = lastPlaybackInfo.mCurrentPosMs;
                if (thenPos < 0) {
                    return -1;
                }

                final long now = SystemClock.elapsedRealtime();
                final long then = lastPlaybackInfo.mStateChangeTimeMs;
                final long sinceThen = now - then;
                final long scaledSinceThen = (long) (sinceThen * lastPlaybackInfo.mSpeed);
                return thenPos + scaledSinceThen;
            }
        }
        return -1;
    
android.media.RemoteController$RcDisplaygetRcDisplay()

hide
Used by AudioManager to access binder to be registered/unregistered inside MediaFocusControl
return

        return mRcd;
    
public java.lang.StringgetRemoteControlClientPackageName()

hide

        if (USE_SESSIONS) {
            synchronized (mInfoLock) {
                return mCurrentSession != null ? mCurrentSession.getPackageName()
                        : null;
            }
        } else {
            return mClientPendingIntentCurrent != null ?
                    mClientPendingIntentCurrent.getCreatorPackage() : null;
        }
    
android.media.RemoteController$OnClientUpdateListenergetUpdateListener()

hide
Used by AudioManager to access user listener receiving the client update notifications
return

        return mOnClientUpdateListener;
    
private voidonClientChange(int genId, boolean clearing)

        synchronized(mGenLock) {
            if (mClientGenerationIdCurrent != genId) {
                return;
            }
        }
        final OnClientUpdateListener l;
        synchronized(mInfoLock) {
            l = mOnClientUpdateListener;
            mMetadataEditor = null;
        }
        if (l != null) {
            l.onClientChange(clearing);
        }
    
private voidonDisplayEnable(boolean enabled)

        final OnClientUpdateListener l;
        synchronized(mInfoLock) {
            mEnabled = enabled;
            l = this.mOnClientUpdateListener;
        }
        if (!enabled) {
            // when disabling, reset all info sent to the user
            final int genId;
            synchronized (mGenLock) {
                genId = mClientGenerationIdCurrent;
            }
            // send "stopped" state, happened "now", playback position is 0, speed 0.0f
            final PlaybackInfo pi = new PlaybackInfo(RemoteControlClient.PLAYSTATE_STOPPED,
                    SystemClock.elapsedRealtime() /*stateChangeTimeMs*/,
                    0 /*currentPosMs*/, 0.0f /*speed*/);
            sendMsg(mEventHandler, MSG_NEW_PLAYBACK_INFO, SENDMSG_REPLACE,
                    genId /*arg1*/, 0 /*arg2, ignored*/, pi /*obj*/, 0 /*delay*/);
            // send "blank" transport control info: no controls are supported
            sendMsg(mEventHandler, MSG_NEW_TRANSPORT_INFO, SENDMSG_REPLACE,
                    genId /*arg1*/, 0 /*arg2, no flags*/,
                    null /*obj, ignored*/, 0 /*delay*/);
            // send dummy metadata with empty string for title and artist, duration of 0
            Bundle metadata = new Bundle(3);
            metadata.putString(String.valueOf(MediaMetadataRetriever.METADATA_KEY_TITLE), "");
            metadata.putString(String.valueOf(MediaMetadataRetriever.METADATA_KEY_ARTIST), "");
            metadata.putLong(String.valueOf(MediaMetadataRetriever.METADATA_KEY_DURATION), 0);
            sendMsg(mEventHandler, MSG_NEW_METADATA, SENDMSG_QUEUE,
                    genId /*arg1*/, 0 /*arg2, ignored*/, metadata /*obj*/, 0 /*delay*/);
        }
    
private voidonNewMediaMetadata(MediaMetadata metadata)

        if (metadata == null) {
            // RemoteController only handles non-null metadata
            return;
        }
        final OnClientUpdateListener l;
        final MetadataEditor metadataEditor;
        // prepare the received Bundle to be used inside a MetadataEditor
        synchronized(mInfoLock) {
            l = mOnClientUpdateListener;
            boolean canRate = mCurrentSession != null
                    && mCurrentSession.getRatingType() != Rating.RATING_NONE;
            long editableKeys = canRate ? MediaMetadataEditor.RATING_KEY_BY_USER : 0;
            Bundle legacyMetadata = MediaSessionLegacyHelper.getOldMetadata(metadata,
                    mArtworkWidth, mArtworkHeight);
            mMetadataEditor = new MetadataEditor(legacyMetadata, editableKeys);
            metadataEditor = mMetadataEditor;
        }
        if (l != null) {
            l.onClientMetadataUpdate(metadataEditor);
        }
    
private voidonNewMetadata(int genId, android.os.Bundle metadata)

param
genId
param
metadata guaranteed to be always non-null

        synchronized(mGenLock) {
            if (mClientGenerationIdCurrent != genId) {
                return;
            }
        }
        final OnClientUpdateListener l;
        final MetadataEditor metadataEditor;
        // prepare the received Bundle to be used inside a MetadataEditor
        final long editableKeys = metadata.getLong(
                String.valueOf(MediaMetadataEditor.KEY_EDITABLE_MASK), 0);
        if (editableKeys != 0) {
            metadata.remove(String.valueOf(MediaMetadataEditor.KEY_EDITABLE_MASK));
        }
        synchronized(mInfoLock) {
            l = mOnClientUpdateListener;
            if ((mMetadataEditor != null) && (mMetadataEditor.mEditorMetadata != null)) {
                if (mMetadataEditor.mEditorMetadata != metadata) {
                    // existing metadata, merge existing and new
                    mMetadataEditor.mEditorMetadata.putAll(metadata);
                }

                mMetadataEditor.putBitmap(MediaMetadataEditor.BITMAP_KEY_ARTWORK,
                        (Bitmap)metadata.getParcelable(
                                String.valueOf(MediaMetadataEditor.BITMAP_KEY_ARTWORK)));
                mMetadataEditor.cleanupBitmapFromBundle(MediaMetadataEditor.BITMAP_KEY_ARTWORK);
            } else {
                mMetadataEditor = new MetadataEditor(metadata, editableKeys);
            }
            metadataEditor = mMetadataEditor;
        }
        if (l != null) {
            l.onClientMetadataUpdate(metadataEditor);
        }
    
private voidonNewPendingIntent(int genId, android.app.PendingIntent pi)

        synchronized(mGenLock) {
            if (mClientGenerationIdCurrent != genId) {
                return;
            }
        }
        synchronized(mInfoLock) {
            mClientPendingIntentCurrent = pi;
        }
    
private voidonNewPlaybackInfo(int genId, android.media.RemoteController$PlaybackInfo pi)

        synchronized(mGenLock) {
            if (mClientGenerationIdCurrent != genId) {
                return;
            }
        }
        final OnClientUpdateListener l;
        synchronized(mInfoLock) {
            l = this.mOnClientUpdateListener;
            mLastPlaybackInfo = pi;
        }
        if (l != null) {
            if (pi.mCurrentPosMs == RemoteControlClient.PLAYBACK_POSITION_ALWAYS_UNKNOWN) {
                l.onClientPlaybackStateUpdate(pi.mState);
            } else {
                l.onClientPlaybackStateUpdate(pi.mState, pi.mStateChangeTimeMs, pi.mCurrentPosMs,
                        pi.mSpeed);
            }
        }
    
private voidonNewPlaybackState(android.media.session.PlaybackState state)

        final OnClientUpdateListener l;
        synchronized (mInfoLock) {
            l = this.mOnClientUpdateListener;
        }
        if (l != null) {
            int playstate = state == null ? RemoteControlClient.PLAYSTATE_NONE : PlaybackState
                    .getRccStateFromState(state.getState());
            if (state == null || state.getPosition() == PlaybackState.PLAYBACK_POSITION_UNKNOWN) {
                l.onClientPlaybackStateUpdate(playstate);
            } else {
                l.onClientPlaybackStateUpdate(playstate, state.getLastPositionUpdateTime(),
                        state.getPosition(), state.getPlaybackSpeed());
            }
            if (state != null) {
                l.onClientTransportControlUpdate(
                        PlaybackState.getRccControlFlagsFromActions(state.getActions()));
            }
        }
    
private voidonNewTransportInfo(int genId, int transportControlFlags)

        synchronized(mGenLock) {
            if (mClientGenerationIdCurrent != genId) {
                return;
            }
        }
        final OnClientUpdateListener l;
        synchronized(mInfoLock) {
            l = mOnClientUpdateListener;
        }
        if (l != null) {
            l.onClientTransportControlUpdate(transportControlFlags);
        }
    
public booleanseekTo(long timeMs)
Sets the new playback position. This method can only be called on a registered RemoteController.

param
timeMs a 0 or positive value for the new playback position, expressed in ms.
return
true if the command to set the playback position was successfully sent.
throws
IllegalArgumentException

        if (!mEnabled) {
            Log.e(TAG, "Cannot use seekTo() from a disabled RemoteController");
            return false;
        }
        if (timeMs < 0) {
            throw new IllegalArgumentException("illegal negative time value");
        }
        synchronized (mInfoLock) {
            if (mCurrentSession != null) {
                mCurrentSession.getTransportControls().seekTo(timeMs);
            }
        }
        return true;
    
public booleansendMediaKeyEvent(android.view.KeyEvent keyEvent)
Send a simulated key event for a media button to be received by the current client. To simulate a key press, you must first send a KeyEvent built with a {@link KeyEvent#ACTION_DOWN} action, then another event with the {@link KeyEvent#ACTION_UP} action.

The key event will be sent to the registered receiver (see {@link AudioManager#registerMediaButtonEventReceiver(PendingIntent)}) whose associated {@link RemoteControlClient}'s metadata and playback state is published (there may be none under some circumstances).

param
keyEvent a {@link KeyEvent} instance whose key code is one of {@link KeyEvent#KEYCODE_MUTE}, {@link KeyEvent#KEYCODE_HEADSETHOOK}, {@link KeyEvent#KEYCODE_MEDIA_PLAY}, {@link KeyEvent#KEYCODE_MEDIA_PAUSE}, {@link KeyEvent#KEYCODE_MEDIA_PLAY_PAUSE}, {@link KeyEvent#KEYCODE_MEDIA_STOP}, {@link KeyEvent#KEYCODE_MEDIA_NEXT}, {@link KeyEvent#KEYCODE_MEDIA_PREVIOUS}, {@link KeyEvent#KEYCODE_MEDIA_REWIND}, {@link KeyEvent#KEYCODE_MEDIA_RECORD}, {@link KeyEvent#KEYCODE_MEDIA_FAST_FORWARD}, {@link KeyEvent#KEYCODE_MEDIA_CLOSE}, {@link KeyEvent#KEYCODE_MEDIA_EJECT}, or {@link KeyEvent#KEYCODE_MEDIA_AUDIO_TRACK}.
return
true if the event was successfully sent, false otherwise.
throws
IllegalArgumentException

        if (!KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
            throw new IllegalArgumentException("not a media key event");
        }
        if (USE_SESSIONS) {
            synchronized (mInfoLock) {
                if (mCurrentSession != null) {
                    return mCurrentSession.dispatchMediaButtonEvent(keyEvent);
                }
                return false;
            }
        } else {
            final PendingIntent pi;
            synchronized (mInfoLock) {
                if (!mIsRegistered) {
                    Log.e(TAG,
                            "Cannot use sendMediaKeyEvent() from an unregistered RemoteController");
                    return false;
                }
                if (!mEnabled) {
                    Log.e(TAG, "Cannot use sendMediaKeyEvent() from a disabled RemoteController");
                    return false;
                }
                pi = mClientPendingIntentCurrent;
            }
            if (pi != null) {
                Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
                try {
                    pi.send(mContext, 0, intent);
                } catch (CanceledException e) {
                    Log.e(TAG, "Error sending intent for media button down: ", e);
                    return false;
                }
            } else {
                Log.i(TAG, "No-op when sending key click, no receiver right now");
                return false;
            }
        }
        return true;
    
private static voidsendMsg(android.os.Handler handler, int msg, int existingMsgPolicy, int arg1, int arg2, java.lang.Object obj, int delayMs)


            
                    
        if (handler == null) {
            Log.e(TAG, "null event handler, will not deliver message " + msg);
            return;
        }
        if (existingMsgPolicy == SENDMSG_REPLACE) {
            handler.removeMessages(msg);
        } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
            return;
        }
        handler.sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delayMs);
    
public booleansetArtworkConfiguration(boolean wantBitmap, int width, int height)

hide
param
wantBitmap
param
width
param
height
return
true if successful
throws
IllegalArgumentException

        synchronized (mInfoLock) {
            if (wantBitmap) {
                if ((width > 0) && (height > 0)) {
                    if (width > mMaxBitmapDimension) { width = mMaxBitmapDimension; }
                    if (height > mMaxBitmapDimension) { height = mMaxBitmapDimension; }
                    mArtworkWidth = width;
                    mArtworkHeight = height;
                } else {
                    throw new IllegalArgumentException("Invalid dimensions");
                }
            } else {
                mArtworkWidth = -1;
                mArtworkHeight = -1;
            }
        }
        return true;
    
public booleansetArtworkConfiguration(int width, int height)
Set the maximum artwork image dimensions to be received in the metadata. No bitmaps will be received unless this has been specified.

param
width the maximum width in pixels
param
height the maximum height in pixels
return
true if the artwork dimension was successfully set.
throws
IllegalArgumentException

        return setArtworkConfiguration(true, width, height);
    
voidsetIsRegistered(boolean registered)

hide
Used by AudioManager to mark this instance as registered.
param
registered

        synchronized (mInfoLock) {
            mIsRegistered = registered;
        }
    
public booleansetSynchronizationMode(int sync)
Set the playback position synchronization mode. Must be called on a registered RemoteController.

param
sync {@link #POSITION_SYNCHRONIZATION_NONE} or {@link #POSITION_SYNCHRONIZATION_CHECK}
return
true if the synchronization mode was successfully set.
throws
IllegalArgumentException


                                        
          
        if ((sync != POSITION_SYNCHRONIZATION_NONE) && (sync != POSITION_SYNCHRONIZATION_CHECK)) {
            throw new IllegalArgumentException("Unknown synchronization mode " + sync);
        }
        if (!mIsRegistered) {
            Log.e(TAG, "Cannot set synchronization mode on an unregistered RemoteController");
            return false;
        }
        mAudioManager.remoteControlDisplayWantsPlaybackPositionSync(mRcd,
                POSITION_SYNCHRONIZATION_CHECK == sync);
        return true;
    
voidstartListeningToSessions()

hide

        final ComponentName listenerComponent = new ComponentName(mContext,
                mOnClientUpdateListener.getClass());
        Handler handler = null;
        if (Looper.myLooper() == null) {
            handler = new Handler(Looper.getMainLooper());
        }
        mSessionManager.addOnActiveSessionsChangedListener(mSessionListener, listenerComponent,
                UserHandle.myUserId(), handler);
        mSessionListener.onActiveSessionsChanged(mSessionManager
                .getActiveSessions(listenerComponent));
        if (DEBUG) {
            Log.d(TAG, "Registered session listener with component " + listenerComponent
                    + " for user " + UserHandle.myUserId());
        }
    
voidstopListeningToSessions()

hide

        mSessionManager.removeOnActiveSessionsChangedListener(mSessionListener);
        if (DEBUG) {
            Log.d(TAG, "Unregistered session listener for user "
                    + UserHandle.myUserId());
        }
    
private voidupdateController(android.media.session.MediaController controller)

        if (DEBUG) {
            Log.d(TAG, "Updating controller to " + controller + " previous controller is "
                    + mCurrentSession);
        }
        synchronized (mInfoLock) {
            if (controller == null) {
                if (mCurrentSession != null) {
                    mCurrentSession.unregisterCallback(mSessionCb);
                    mCurrentSession = null;
                    sendMsg(mEventHandler, MSG_CLIENT_CHANGE, SENDMSG_REPLACE,
                            0 /* genId */, 1 /* clearing */, null /* obj */, 0 /* delay */);
                }
            } else if (mCurrentSession == null
                    || !controller.getSessionToken()
                            .equals(mCurrentSession.getSessionToken())) {
                if (mCurrentSession != null) {
                    mCurrentSession.unregisterCallback(mSessionCb);
                }
                sendMsg(mEventHandler, MSG_CLIENT_CHANGE, SENDMSG_REPLACE,
                        0 /* genId */, 0 /* clearing */, null /* obj */, 0 /* delay */);
                mCurrentSession = controller;
                mCurrentSession.registerCallback(mSessionCb, mEventHandler);

                PlaybackState state = controller.getPlaybackState();
                sendMsg(mEventHandler, MSG_NEW_PLAYBACK_STATE, SENDMSG_REPLACE,
                        0 /* genId */, 0, state /* obj */, 0 /* delay */);

                MediaMetadata metadata = controller.getMetadata();
                sendMsg(mEventHandler, MSG_NEW_MEDIA_METADATA, SENDMSG_REPLACE,
                        0 /* arg1 */, 0 /* arg2 */, metadata /* obj */, 0 /* delay */);
            }
            // else same controller, no need to update
        }