MediaController

public class MediaController
extends Object implements AutoCloseable

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.

Topic covered here:

  1. Controller Lifecycle

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.

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 the way volume is handled for this session. 

Public methods

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

Adds the media item to the playlist at the index with the media ID.

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

Adjust the volume of the output this session is playing on.

void close()

Release this object, and disconnect from the session.

ListenableFuture<SessionResult> fastForward()

Requests session to increase the playback speed.

long getBufferedPosition()

Gets the lastly cached buffered position from the session when MediaController.ControllerCallback.onBufferingStateChanged(MediaController, MediaItem, int) is called.

int getBufferingState()

Gets the current buffering state of the player.

SessionToken getConnectedToken()

Returns SessionToken of the connected session.

MediaItem getCurrentMediaItem()

Gets the lastly cached current item from MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem).

int getCurrentMediaItemIndex()

Gets the current item index in the playlist.

long getCurrentPosition()

Gets the current playback position.

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.

MediaController.PlaybackInfo getPlaybackInfo()

Get the current playback info for this session.

float getPlaybackSpeed()

Get the lastly cached playback speed from MediaController.ControllerCallback.onPlaybackSpeedChanged(MediaController, float).

int getPlayerState()

Get the lastly cached player state from MediaController.ControllerCallback.onPlayerStateChanged(MediaController, int).

List<MediaItem> getPlaylist()

Returns the cached playlist from MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata).

MediaMetadata getPlaylistMetadata()

Gets the lastly cached playlist metadata either from MediaController.ControllerCallback.onPlaylistMetadataChanged(MediaController, MediaMetadata) or MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata).

int getPreviousMediaItemIndex()

Gets the previous item index in the playlist.

int getRepeatMode()

Gets the cached repeat mode from the MediaController.ControllerCallback.onRepeatModeChanged(MediaController, int).

PendingIntent getSessionActivity()

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

int getShuffleMode()

Gets the cached shuffle mode from the MediaController.ControllerCallback.onShuffleModeChanged(MediaController, int).

boolean isConnected()

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

ListenableFuture<SessionResult> pause()

Requests that the player pauses playback.

ListenableFuture<SessionResult> play()

Requests that the player starts or resumes playback.

ListenableFuture<SessionResult> prepare()

Requests that the player prepares the media items for playback.

ListenableFuture<SessionResult> removePlaylistItem(int index)

Removes the media item at index in the playlist.

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

Replaces the media item at index in the playlist with the media ID.

ListenableFuture<SessionResult> rewind()

Requests session to decrease the playback speed.

ListenableFuture<SessionResult> seekTo(long pos)

Move to a new location in the media stream.

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

Send 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)

Sets a MediaItem for playback with the media ID.

ListenableFuture<SessionResult> setPlaybackSpeed(float speed)

Sets the playback speed.

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

Sets the playlist with the list of media IDs.

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

Rate the media.

ListenableFuture<SessionResult> setRepeatMode(int repeatMode)

Sets the repeat mode.

ListenableFuture<SessionResult> setShuffleMode(int shuffleMode)

Sets the shuffle mode.

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

Set the volume of the output this session is playing on.

ListenableFuture<SessionResult> skipBackward()

Requests session to skip forward within the current media item.

ListenableFuture<SessionResult> skipForward()

Requests session to skip backward within the current media item.

ListenableFuture<SessionResult> skipToNextPlaylistItem()

Skips to the next item in the playlist.

ListenableFuture<SessionResult> skipToPlaylistItem(int index)

Skips to the item in the playlist at the index.

ListenableFuture<SessionResult> skipToPreviousPlaylistItem()

Skips to the previous item in the playlist.

ListenableFuture<SessionResult> updatePlaylistMetadata(MediaMetadata metadata)

Updates the playlist metadata

Inherited methods

Public methods

addPlaylistItem

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

Adds the media item to the playlist at the index with the media ID. Index equals or greater than the current playlist size (e.g. Integer.MAX_VALUE) will add the item at the end of the playlist.

This will not change the currently playing media item. If index is less than or equal to the current index of the playlist, the current index of the playlist will be incremented correspondingly.

Parameters
index int: the index you want to add

mediaId String: The non-empty media id of the new item

Returns
ListenableFuture<SessionResult>

adjustVolume

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

Adjust the volume of the output this session is playing on. The direction must be one of AudioManager.ADJUST_LOWER, AudioManager.ADJUST_RAISE, or AudioManager.ADJUST_SAME.

The command will be ignored if the session does not support VolumeProviderCompat.VOLUME_CONTROL_RELATIVE or VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE.

If the session is local playback, this changes the device's volume with the stream that session's player is using. Flags will be specified for the AudioManager.

If the session is remote player (i.e. session has set volume provider), its volume provider will receive this request instead.

Parameters
direction int: The direction to adjust the volume in.

flags int: flags from AudioManager to include with the volume request for local playback

Returns
ListenableFuture<SessionResult>

See also:

close

public void close ()

Release this object, and disconnect from the session. After this, callbacks wouldn't be received.

fastForward

public ListenableFuture<SessionResult> fastForward ()

Requests session to increase the playback speed.

Returns
ListenableFuture<SessionResult>

getBufferedPosition

public long getBufferedPosition ()

Gets the lastly cached buffered position from the session when MediaController.ControllerCallback.onBufferingStateChanged(MediaController, MediaItem, int) is called.

Returns
long buffering position in millis, or SessionPlayer.UNKNOWN_TIME if unknown or not connected

getBufferingState

public int getBufferingState ()

Gets the current buffering state of the player. During buffering, see getBufferedPosition() for the quantifying the amount already buffered.

Returns
int the buffering state, or SessionPlayer.BUFFERING_STATE_UNKNOWN if unknown or not connected

getConnectedToken

public SessionToken getConnectedToken ()

Returns SessionToken of the connected session. If it is not connected yet, it returns null.

This may differ with the SessionToken from the constructor. For example, if the controller is created with the token for MediaSessionService, this would return token for the MediaSession in the service.

Returns
SessionToken SessionToken of the connected session, or null if not connected

getCurrentMediaItem

public MediaItem getCurrentMediaItem ()

Gets the lastly cached current item from MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem).

Returns
MediaItem the currently playing item, or null if unknown or not connected

getCurrentMediaItemIndex

public int getCurrentMediaItemIndex ()

Gets the current item index in the playlist. The returned value can be outdated after MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem) or MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata) is called.

Returns
int the index of current item in playlist, or -1 if current media item does not exist or playlist hasn't been set.

getCurrentPosition

public long getCurrentPosition ()

Gets the current playback position.

This returns the calculated value of the position, based on the difference between the update time and current time.

Returns
long the current playback position in ms, or SessionPlayer.UNKNOWN_TIME if unknown or not connected

getDuration

public long getDuration ()

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

Returns
long the duration in ms, or SessionPlayer.UNKNOWN_TIME

getNextMediaItemIndex

public int getNextMediaItemIndex ()

Gets the next item index in the playlist. The returned value can be outdated after MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem) or MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata) is called.

Interoperability: When connected to MediaSessionCompat, this will always return -1.

Returns
int the index of next item in playlist, or -1 if next media item does not exist or playlist hasn't been set.

getPlaybackInfo

public MediaController.PlaybackInfo getPlaybackInfo ()

Get the current playback info for this session. If it is not connected yet, it returns null.

Returns
MediaController.PlaybackInfo The current playback info or null

getPlaybackSpeed

public float getPlaybackSpeed ()

Get the lastly cached playback speed from MediaController.ControllerCallback.onPlaybackSpeedChanged(MediaController, float).

Returns
float speed the lastly cached playback speed, or 0f if unknown or not connected

getPlayerState

public int getPlayerState ()

Get the lastly cached player state from MediaController.ControllerCallback.onPlayerStateChanged(MediaController, int). If it is not connected yet, it returns SessionPlayer.PLAYER_STATE_IDLE.

Returns
int player state

getPlaylist

public List<MediaItem> getPlaylist ()

Returns the cached playlist from MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata). Can be null if the playlist hasn't been set or it's reset by setMediaItem(String).

This list may differ with the list that was specified with setPlaylist(List, MediaMetadata) depending on the SessionPlayer implementation. Use media items returned here for other playlist agent APIs such as SessionPlayer.skipToPlaylistItem(int).

Returns
List<MediaItem> playlist, or null if the playlist hasn't been set, controller isn't connected, or it doesn't have enough permission.

getPlaylistMetadata

public MediaMetadata getPlaylistMetadata ()

Gets the lastly cached playlist metadata either from MediaController.ControllerCallback.onPlaylistMetadataChanged(MediaController, MediaMetadata) or MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata).

Returns
MediaMetadata metadata metadata of the playlist, or null if none is set or the controller is not connected

getPreviousMediaItemIndex

public int getPreviousMediaItemIndex ()

Gets the previous item index in the playlist. The returned value can be outdated after MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem) or MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata) is called.

Interoperability: When connected to MediaSessionCompat, this will always return -1.

Returns
int the index of previous item in playlist, or -1 if previous media item does not exist or playlist hasn't been set.

getRepeatMode

public int getRepeatMode ()

Gets the cached repeat mode from the MediaController.ControllerCallback.onRepeatModeChanged(MediaController, int). If it is not connected yet, it returns SessionPlayer.REPEAT_MODE_NONE.

Returns
int repeat mode

getSessionActivity

public PendingIntent getSessionActivity ()

Get an intent for launching UI associated with this session if one exists. If it is not connected yet, it returns null.

Returns
PendingIntent A PendingIntent to launch UI or null

getShuffleMode

public int getShuffleMode ()

Gets the cached shuffle mode from the MediaController.ControllerCallback.onShuffleModeChanged(MediaController, int). If it is not connected yet, it returns SessionPlayer.SHUFFLE_MODE_NONE.

Returns
int The shuffle mode

isConnected

public boolean isConnected ()

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

Returns
boolean

pause

public ListenableFuture<SessionResult> pause ()

Requests that the player pauses playback.

This would transfer the player state from SessionPlayer.PLAYER_STATE_PLAYING to SessionPlayer.PLAYER_STATE_PAUSED.

Returns
ListenableFuture<SessionResult>

play

public ListenableFuture<SessionResult> play ()

Requests that the player starts or resumes playback.

If the player state is SessionPlayer.PLAYER_STATE_IDLE, the session would also call SessionPlayer.prepare() and then SessionPlayer.play() to start playback. If you want to have finer grained control of the playback start call prepare() manually before this. Calling prepare() in advance would help this method to start playback faster and also help to take audio focus at the last moment.

Returns
ListenableFuture<SessionResult>

See also:

prepare

public ListenableFuture<SessionResult> prepare ()

Requests that the player prepares the media items for playback.

This would transfer the player state from SessionPlayer.PLAYER_STATE_IDLE to SessionPlayer.PLAYER_STATE_PAUSED.

Playback can be started without this. But this provides finer grained control of playback start. See play() for details.

Returns
ListenableFuture<SessionResult>

See also:

removePlaylistItem

public ListenableFuture<SessionResult> removePlaylistItem (int index)

Removes the media item at index in the playlist.

If the item is the currently playing item of the playlist, current playback will be stopped and playback moves to next source in the list.

Parameters
index int: the media item you want to add

Returns
ListenableFuture<SessionResult>

replacePlaylistItem

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

Replaces the media item at index in the playlist with the media ID.

Parameters
index int: the index of the item to replace

mediaId String: The non-empty media id of the new item

Returns
ListenableFuture<SessionResult>

rewind

public ListenableFuture<SessionResult> rewind ()

Requests session to decrease the playback speed.

Returns
ListenableFuture<SessionResult>

seekTo

public ListenableFuture<SessionResult> seekTo (long pos)

Move to a new location in the media stream.

Parameters
pos long: Position to move to, in milliseconds.

Returns
ListenableFuture<SessionResult>

sendCustomCommand

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

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

A command is not accepted if it is not a custom command.

Parameters
command SessionCommand: custom command

args Bundle: optional argument

Returns
ListenableFuture<SessionResult>

setMediaItem

public ListenableFuture<SessionResult> setMediaItem (String mediaId)

Sets a MediaItem for playback with the media ID. Use this or setPlaylist(List, MediaMetadata) to specify which items to play. If you want to change current item in the playlist, use one of skipToPlaylistItem(int), skipToNextPlaylistItem(), or skipToPreviousPlaylistItem() instead of this method.

The MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata) and MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem) would be called when it's completed. The current item would be the item given here.

Parameters
mediaId String: The non-empty media id of the item to play

Returns
ListenableFuture<SessionResult>

setPlaybackSpeed

public ListenableFuture<SessionResult> setPlaybackSpeed (float speed)

Sets the playback speed. A value of 1.0f is the default playback value, and a negative value indicates reverse playback. 0.0f is not allowed.

Parameters
speed float

Returns
ListenableFuture<SessionResult>

Throws
IllegalArgumentException if the speed is equal to zero.

setPlaylist

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

Sets the playlist with the list of media IDs. Use this or setMediaItem(String) to specify which items to play.

All media IDs in the list shouldn't be an empty string.

The MediaController.ControllerCallback.onPlaylistChanged(MediaController, List, MediaMetadata) and MediaController.ControllerCallback.onCurrentMediaItemChanged(MediaController, MediaItem) would be called when it's completed. The current item would be the first item in the playlist.

Parameters
list List: list of media id. Shouldn't contain an empty id.

metadata MediaMetadata: metadata of the playlist

Returns
ListenableFuture<SessionResult>

Throws
IllegalArgumentException if the list is null or contains any empty string.

setRating

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

Rate the media. This will cause the rating to be set for the current user. The rating style must follow the user rating style from the session. You can get the rating style from the session through the MediaMetadata.getRating(String) with the key MediaMetadata.METADATA_KEY_USER_RATING.

If the user rating was null, the media item does not accept setting user rating.

Parameters
mediaId String: The non-empty media id

rating Rating: The rating to set

Returns
ListenableFuture<SessionResult>

setRepeatMode

public ListenableFuture<SessionResult> setRepeatMode (int repeatMode)

Sets the repeat mode.

Parameters
repeatMode int: repeat mode

Returns
ListenableFuture<SessionResult>

setShuffleMode

public ListenableFuture<SessionResult> setShuffleMode (int shuffleMode)

Sets the shuffle mode.

Parameters
shuffleMode int: The shuffle mode

Returns
ListenableFuture<SessionResult>

setVolumeTo

public ListenableFuture<SessionResult> setVolumeTo (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 VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE.

If the session is local playback, this changes the device's volume with the stream that session's player is using. Flags will be specified for the AudioManager.

If the session is remote player (i.e. session has set volume provider), its volume provider will receive this request instead.

Parameters
value int: The value to set it to, between 0 and the reported max.

flags int: flags from AudioManager to include with the volume request for local playback

Returns
ListenableFuture<SessionResult>

See also:

skipBackward

public ListenableFuture<SessionResult> skipBackward ()

Requests session to skip forward within the current media item.

Returns
ListenableFuture<SessionResult>

skipForward

public ListenableFuture<SessionResult> skipForward ()

Requests session to skip backward within the current media item.

Returns
ListenableFuture<SessionResult>

skipToNextPlaylistItem

public ListenableFuture<SessionResult> skipToNextPlaylistItem ()

Skips to the next item in the playlist.

This calls SessionPlayer.skipToNextPlaylistItem().

Returns
ListenableFuture<SessionResult>

skipToPlaylistItem

public ListenableFuture<SessionResult> skipToPlaylistItem (int index)

Skips to the item in the playlist at the index.

This calls SessionPlayer.skipToPlaylistItem(int).

Parameters
index int: The item in the playlist you want to play

Returns
ListenableFuture<SessionResult>

skipToPreviousPlaylistItem

public ListenableFuture<SessionResult> skipToPreviousPlaylistItem ()

Skips to the previous item in the playlist.

This calls SessionPlayer.skipToPreviousPlaylistItem().

Returns
ListenableFuture<SessionResult>

updatePlaylistMetadata

public ListenableFuture<SessionResult> updatePlaylistMetadata (MediaMetadata metadata)

Updates the playlist metadata

Parameters
metadata MediaMetadata: metadata of the playlist

Returns
ListenableFuture<SessionResult>