MediaController

public class MediaController
extends Object implements Closeable

java.lang.Object
   ↳ androidx.media2.session.MediaController


Allows an app to interact with an active MediaSession or a MediaSessionService which would provide MediaSession. Media buttons and other commands can be sent to the session.

MediaController objects are thread-safe.

Topics covered here:

  1. Controller Lifecycle
  2. Controlling the MediaSession in the same process

Controller Lifecycle

When a controller is created with the SessionToken for a MediaSession (i.e. session token type is SessionToken.TYPE_SESSION), the controller will connect to the specific session.

When a controller is created with the SessionToken for a MediaSessionService (i.e. session token type is SessionToken.TYPE_SESSION_SERVICE or SessionToken.TYPE_LIBRARY_SERVICE), the controller binds to the service for connecting to a MediaSession in it. MediaSessionService will provide a session to connect.

When a controller connects to a session, MediaSession.SessionCallback.onConnect(MediaSession, MediaSession.ControllerInfo) will be called to either accept or reject the connection. Wait MediaController.ControllerCallback.onConnected(MediaController, SessionCommandGroup) or MediaController.ControllerCallback.onDisconnected(MediaController) for the result.

When the connected session is closed, the controller will receive MediaController.ControllerCallback.onDisconnected(MediaController).

When you're done, use close() to clean up resources. This also helps session service to be destroyed when there's no controller associated with it.

Controlling the MediaSession in the same process

When you control the MediaSession and its SessionPlayer, it's recommended to use them directly rather than creating MediaController. However, if you need to use MediaController in the same process, be careful not to block session callback executor's thread. Here's an example code that would never return due to the thread issue.

 // Code runs on the main thread.
 MediaSession session = new MediaSession.Builder(context, player)
    .setSessionCallback(sessionCallback, Context.getMainExecutor(context)).build();
 MediaController controller = new MediaController.Builder(context)
    .setSessionToken(session.getToken())
    .setControllerCallback(Context.getMainExecutor(context), controllerCallback)
    .build();

 // This will hang and never return.
 controller.play().get();
When a session gets a command from a controller, the session's MediaSession.SessionCallback.onCommandRequest(MediaSession, MediaSession.ControllerInfo, SessionCommand) would be executed on the session's callback executor to decide whether to ignore or handle the incoming command. To do so, the session's callback executor shouldn't be blocked to handle the incoming calls. However, if you call Future.get() on the thread for the session callback executor, then your call wouldn't be executed and never return.

To avoid such issue, don't block the session callback executor's thread. Creating a dedicated thread for the session callback executor would be helpful. See Executors.newSingleThreadExecutor() for creating a new thread.

Summary

Nested classes

class MediaController.Builder

Builder for MediaController

class MediaController.ControllerCallback

Interface for listening to change in activeness of the MediaSession

class MediaController.PlaybackInfo

Holds information about the way volume is handled for this session. 

Public methods

ListenableFuture<SessionResult> addPlaylistItem(int index, String mediaId)

Requests that the SessionPlayer associated with the connected MediaSession adds the media item to the playlist at the index with the media ID.

ListenableFuture<SessionResult> adjustVolume(int direction, int flags)

Requests that the connected MediaSession adjusts the volume of the output that is playing on.

void close()

Releases this object, and disconnects from the session.

ListenableFuture<SessionResult> deselectTrack(SessionPlayer.TrackInfo trackInfo)

Requests that the SessionPlayer associated with the connected MediaSession deselects the SessionPlayer.TrackInfo for the current media item.

ListenableFuture<SessionResult> fastForward()

Requests that the SessionPlayer associated with the connected MediaSession to fast forward playback.

SessionCommandGroup getAllowedCommands()

Gets the cached allowed commands from MediaController.ControllerCallback.onAllowedCommandsChanged(MediaController, SessionCommandGroup).

long getBufferedPosition()

Gets the position for how much has been buffered of the SessionPlayer associated with the connected MediaSession, or SessionPlayer.UNKNOWN_TIME if unknown or not connected.

int getBufferingState()

Gets the current buffering state of the SessionPlayer associated with the connected MediaSession.

SessionToken getConnectedToken()

Returns the SessionToken of the connected session.

MediaItem getCurrentMediaItem()

Gets the current media item of the SessionPlayer associated with the connected MediaSession.

int getCurrentMediaItemIndex()

Gets the current item index in the playlist of the SessionPlayer associated with the connected MediaSession.

long getCurrentPosition()

Gets the playback position of the SessionPlayer associated with the connected MediaSession.

long getDuration()

Gets the duration of the current media item, or SessionPlayer.UNKNOWN_TIME if unknown or not connected.

int getNextMediaItemIndex()

Gets the next item index in the playlist of the SessionPlayer associated with the connected MediaSession.

MediaController.PlaybackInfo getPlaybackInfo()

Get the current playback info for this session.

float getPlaybackSpeed()

Gets the playback speed to be used by the of the SessionPlayer associated with the connected MediaSession when playing.

int getPlayerState()

Gets the state of the SessionPlayer associated with the connected MediaSession.

List<MediaItem> getPlaylist()

Gets the playlist of the SessionPlayer associated with the connected MediaSession.

MediaMetadata getPlaylistMetadata()

Gets the playlist metadata of the SessionPlayer associated with the connected MediaSession.

int getPreviousMediaItemIndex()

Gets the previous item index in the playlist of the SessionPlayer associated with the connected MediaSession.

int getRepeatMode()

Gets the repeat mode of the SessionPlayer associated with the connected MediaSession.

SessionPlayer.TrackInfo getSelectedTrack(int trackType)

Gets the currently selected track for the given track type of the SessionPlayer associated with the connected MediaSession.

PendingIntent getSessionActivity()

Gets an intent for launching UI associated with this session if one exists.

int getShuffleMode()

Gets the shuffle mode of the SessionPlayer associated with the connected MediaSession.

List<SessionPlayer.TrackInfo> getTracks()

Gets the full list of selected and unselected tracks that the media contains of the SessionPlayer associated with the connected MediaSession.

VideoSize getVideoSize()

Gets the video size of the SessionPlayer associated with the connected MediaSession.

boolean isConnected()

Returns whether this class is connected to active MediaSession or not.

ListenableFuture<SessionResult> movePlaylistItem(int fromIndex, int toIndex)

Requests that the SessionPlayer associated with the connected MediaSession moves the media item at fromIdx to toIdx in the playlist.

ListenableFuture<SessionResult> pause()

Requests that the SessionPlayer associated with the connected MediaSession pauses playback.

ListenableFuture<SessionResult> play()

Requests that the SessionPlayer associated with the connected MediaSession starts or resumes playback.

ListenableFuture<SessionResult> prepare()

Requests that the SessionPlayer associated with the connected MediaSession prepares the media items for playback.

ListenableFuture<SessionResult> removePlaylistItem(int index)

Requests that the SessionPlayer associated with the connected MediaSession removes the media item at index in the playlist.

ListenableFuture<SessionResult> replacePlaylistItem(int index, String mediaId)

Requests that the SessionPlayer associated with the connected MediaSession replaces the media item at index in the playlist with the media ID.

ListenableFuture<SessionResult> rewind()

Requests that the SessionPlayer associated with the connected MediaSession to rewind playback.

ListenableFuture<SessionResult> seekTo(long position)

Requests that the SessionPlayer associated with the connected MediaSession seeks to the specified position.

ListenableFuture<SessionResult> selectTrack(SessionPlayer.TrackInfo trackInfo)

Requests that the SessionPlayer associated with the connected MediaSession selects the SessionPlayer.TrackInfo for the current media item.

ListenableFuture<SessionResult> sendCustomCommand(SessionCommand command, Bundle args)

Sends a custom command to the session

Interoperability: When connected to MediaSessionCompat, SessionResult.getResultCode() will return the custom result code from the ResultReceiver.onReceiveResult(int, Bundle) instead of the standard result codes defined in the SessionResult.

ListenableFuture<SessionResult> setMediaItem(String mediaId)

Requests that the SessionPlayer associated with the connected MediaSession sets a MediaItem for playback.

ListenableFuture<SessionResult> setMediaUri(Uri uri, Bundle extras)

Requests that the connected MediaSession sets a specific Uri for playback.

ListenableFuture<SessionResult> setPlaybackSpeed(float playbackSpeed)

Requests that the SessionPlayer associated with the connected MediaSession sets the playback speed.

ListenableFuture<SessionResult> setPlaylist(List<String> list, MediaMetadata metadata)

Requests that the SessionPlayer associated with the connected MediaSession sets the playlist with the list of media IDs.

ListenableFuture<SessionResult> setRating(String mediaId, Rating rating)

Requests that the connected MediaSession rates the media.

ListenableFuture<SessionResult> setRepeatMode(int repeatMode)

Requests that the SessionPlayer associated with the connected MediaSession sets the repeat mode.

ListenableFuture<SessionResult> setShuffleMode(int shuffleMode)

Requests that the SessionPlayer associated with the connected MediaSession sets the shuffle mode.

ListenableFuture<SessionResult> setSurface(Surface surface)

Requests that the SessionPlayer associated with the connected MediaSession sets the Surface to be used as the sink for the video portion of the media.

ListenableFuture<SessionResult> setVolumeTo(int value, int flags)

Requests that the connected MediaSession sets the volume of the output that is playing on.

ListenableFuture<SessionResult> skipBackward()

Requests that the SessionPlayer associated with the connected MediaSession skips forward within the current media item.

ListenableFuture<SessionResult> skipForward()

Requests that the SessionPlayer associated with the connected MediaSession skips backward within the current media item.

ListenableFuture<SessionResult> skipToNextPlaylistItem()

Requests that the SessionPlayer associated with the connected MediaSession skips to the next item in the playlist.

ListenableFuture<SessionResult> skipToPlaylistItem(int index)

Requests that the SessionPlayer associated with the connected MediaSession skips to the item in the playlist at the index.

ListenableFuture<SessionResult> skipToPreviousPlaylistItem()

Requests that the SessionPlayer associated with the connected MediaSession skips to the previous item in the playlist.

ListenableFuture<SessionResult> updatePlaylistMetadata(MediaMetadata metadata)

Requests that the SessionPlayer associated with the connected MediaSession updates the playlist metadata while keeping th