MediaController

Added in 1.0.0
Deprecated in 1.3.0

public class MediaController implements Closeable

Known direct subclasses
MediaBrowser

This class is deprecated.

androidx.media2 is deprecated.


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
  3. Package Visibility Filter

Controller Lifecycle

When a controller is created with the SessionToken for a MediaSession (i.e. session token type is 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 TYPE_SESSION_SERVICE or 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, onConnect will be called to either accept or reject the connection. Wait onConnected or onDisconnected for the result.

When the connected session is closed, the controller will receive onDisconnected.

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 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 onCommandRequest 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 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 newSingleThreadExecutor for creating a new thread.

Package Visibility Filter

The app targeting API level 30 or higher must include a <queries> element in their manifest to connect to a service component of another app like MediaSessionService, MediaLibraryService, or androidx.media.MediaBrowserServiceCompat). See the following example and this guide for more information.

<!-- As intent actions -->
<intent>
  <action android:name="androidx.media2.session.MediaSessionService" />
</intent>
<intent>
  <action android:name="androidx.media2.session.MediaLibraryService" />
</intent>
<intent>
  <action android:name="android.media.browse.MediaBrowserService" />
</intent>
<!-- Or, as a package name -->
<package android:name="package_name_of_the_other_app" />

Summary

Nested types

public final class MediaController.Builder

This class is deprecated.

androidx.media2 is deprecated.

This class is deprecated.

androidx.media2 is deprecated.

This class is deprecated.

androidx.media2 is deprecated.

Public methods

@NonNull ListenableFuture<SessionResult>
addPlaylistItem(@IntRange(from = 0) int index, @NonNull 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.

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

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

void

Releases this object, and disconnects from the session.

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

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

@Nullable SessionCommandGroup

Gets the cached allowed commands from onAllowedCommandsChanged.

long

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

int

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

@Nullable SessionToken

Returns the SessionToken of the connected session.

@Nullable MediaItem

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

int

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

long

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

long

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

int

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

@Nullable MediaController.PlaybackInfo

Get the current playback info for this session.

float

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

int

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

@Nullable List<MediaItem>

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

@Nullable MediaMetadata

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

int

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

int

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

@Nullable SessionPlayer.TrackInfo
getSelectedTrack(int trackType)

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

@Nullable PendingIntent

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

int

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

@NonNull List<SessionPlayer.TrackInfo>

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

@NonNull VideoSize

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

boolean

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

@NonNull ListenableFuture<SessionResult>
movePlaylistItem(
    @IntRange(from = 0) int fromIndex,
    @IntRange(from = 0) int toIndex
)

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>
removePlaylistItem(@IntRange(from = 0) int index)

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

@NonNull ListenableFuture<SessionResult>
replacePlaylistItem(@IntRange(from = 0) int index, @NonNull String mediaId)

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>
seekTo(long position)

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

Sends a custom command to the session

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>
setPlaybackSpeed(float playbackSpeed)

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

@NonNull ListenableFuture<SessionResult>

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

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

Requests that the connected MediaSession rates the media.

@NonNull ListenableFuture<SessionResult>
setRepeatMode(int repeatMode)

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

@NonNull ListenableFuture<SessionResult>
setShuffleMode(int shuffleMode)

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

@NonNull ListenableFuture<SessionResult>

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.

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

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>
skipToPlaylistItem(@IntRange(from = 0) int index)

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

@NonNull ListenableFuture<SessionResult>

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

@NonNull ListenableFuture<SessionResult>

Requests that the SessionPlayer associated with the connected MediaSession updates the playlist metadata while keeping the playlist as-is.

Public methods

addPlaylistItem

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionResultaddPlaylistItem(@IntRange(from = 0) int index, @NonNull 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. Index equals to or greater than the current playlist size (e.g. MAX_VALUE) will add the item at the end of the playlist.

If index is less than or equal to the current index of the playlist, the current index of the playlist will be increased correspondingly.

On success, a SessionResult would be returned with item added.

Parameters
@IntRange(from = 0) int index

the index you want to add

@NonNull String mediaId

the non-empty media id of the new item

adjustVolume

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionResultadjustVolume(int direction, int flags)

Requests that the connected MediaSession adjusts the volume of the output that is playing on. The direction must be one of ADJUST_LOWER, ADJUST_RAISE, or ADJUST_SAME.

The command will be ignored if the session does not support VOLUME_CONTROL_RELATIVE or 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
int direction

the direction to adjust the volume in

int flags

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

Returns
@NonNull ListenableFuture<SessionResult>

a ListenableFuture representing the pending completion of the command

See also
getPlaybackInfo

close

Added in 1.0.0
Deprecated in 1.3.0
public void close()

Releases this object, and disconnects from the session. After this, callbacks wouldn't be received.

deselectTrack

Added in 1.1.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionResultdeselectTrack(@NonNull SessionPlayer.TrackInfo trackInfo)

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

Generally, a track should already be selected in order to be deselected and audio and video tracks should not be deselected.

The types of tracks supported may vary based on players.

Note: getSelectedTrack returns the currently selected track per track type that can be deselected, but the list may be invalidated when onTracksChanged is called.

Parameters
@NonNull SessionPlayer.TrackInfo trackInfo

track to be deselected

Returns
@NonNull ListenableFuture<SessionResult>

a ListenableFuture which represents the pending completion of the command

fastForward

Added in 1.0.0
Deprecated in 1.3.0
public @NonNull ListenableFuture<SessionResultfastForward()

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

The implementation may be different depending on the players. For example, it can be implemented by seeking forward once, series of seeking forward, or increasing playback speed. If you need full control, then use seekTo or setPlaybackSpeed directly.

Returns
@NonNull ListenableFuture<SessionResult>

a ListenableFuture representing the pending completion of the command

See also
onFastForward

getAllowedCommands

Added in 1.1.0
Deprecated in 1.3.0
public @Nullable SessionCommandGroup getAllowedCommands()

Gets the cached allowed commands from onAllowedCommandsChanged. If it is not connected yet, it returns null.

Returns
@Nullable SessionCommandGroup

the allowed commands

getBufferedPosition

Added in 1.0.0
Deprecated in 1.3.0
public long getBufferedPosition()

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

Returns
long

buffering position in ms, or UNKNOWN_TIME if unknown or not connected

getBufferingState

Added in 1.0.0
Deprecated in 1.3.0
public int getBufferingState()

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

The position is the relative position based on the getStartPosition. So the position 0 means the start position of the MediaItem.

Returns
int

the buffering state, or BUFFERING_STATE_UNKNOWN if unknown or not connected

getConnectedToken

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable SessionToken getConnectedToken()

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

This may differ from 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
@Nullable SessionToken

SessionToken of the connected session, or null if not connected

getCurrentMediaItem

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaItem getCurrentMediaItem()

Gets the current media item of the SessionPlayer associated with the connected MediaSession. This can be currently playing or would be played with later play. This value may be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Returns
@Nullable MediaItem

the current media item. Can be null only when media item or playlist hasn't been set or the controller is not connected.

getCurrentMediaItemIndex

Added in 1.0.0
Deprecated in 1.3.0
public int getCurrentMediaItemIndex()

Gets the current item index in the playlist of the SessionPlayer associated with the connected MediaSession. The value would be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Returns
int

the index of current item in playlist, or INVALID_ITEM_INDEX if current media item does not exist or playlist hasn't been set

getCurrentPosition

Added in 1.0.0
Deprecated in 1.3.0
public long getCurrentPosition()

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

The position is the relative position based on the getStartPosition. So the position 0 means the start position of the MediaItem.

Returns
long

the current playback position in ms, or UNKNOWN_TIME if unknown or not connected

getDuration

Added in 1.0.0
Deprecated in 1.3.0
public long getDuration()

Gets the duration of the current media item, or UNKNOWN_TIME if unknown or not connected. If the current MediaItem has either start or end position, then duration would be adjusted accordingly instead of returning the whole size of the MediaItem.

Returns
long

the duration in ms, or UNKNOWN_TIME if unknonw or not connected.

getNextMediaItemIndex

Added in 1.0.0
Deprecated in 1.3.0
public int getNextMediaItemIndex()

Gets the next item index in the playlist of the SessionPlayer associated with the connected MediaSession. This value would be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Interoperability: When connected to android.support.v4.media.session.MediaSessionCompat, this will always return INVALID_ITEM_INDEX..

Returns
int

the index of next item in playlist, or INVALID_ITEM_INDEX if next media item does not exist or playlist hasn't been set

getPlaybackInfo

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaController.PlaybackInfo getPlaybackInfo()

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

Returns
@Nullable MediaController.PlaybackInfo

the current playback info or null

getPlaybackSpeed

Added in 1.0.0
Deprecated in 1.3.0
public float getPlaybackSpeed()

Gets the playback speed to be used by the of the SessionPlayer associated with the connected MediaSession when playing. A value of 1.0f is the default playback value, and a negative value indicates reverse playback.

Note that it may differ from the speed set in setPlaybackSpeed.

Returns
float

speed the playback speed, or 0f if unknown or not connected

getPlayerState

Added in 1.0.0
Deprecated in 1.3.0
public int getPlayerState()

Gets the state of the SessionPlayer associated with the connected MediaSession. If it is not connected yet, it returns PLAYER_STATE_IDLE.

Returns
int

the player state

getPlaylist

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable List<MediaItemgetPlaylist()

Gets the playlist of the SessionPlayer associated with the connected MediaSession. It can be null if the playlist hasn't been set or it's reset by setMediaItem.

This list may differ from the list that was specified with setPlaylist depending on the SessionPlayer implementation.

Returns
@Nullable List<MediaItem>

playlist, or null if the playlist hasn't been set or the controller isn't connected

getPlaylistMetadata

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable MediaMetadata getPlaylistMetadata()

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

Returns
@Nullable MediaMetadata

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

getPreviousMediaItemIndex

Added in 1.0.0
Deprecated in 1.3.0
public int getPreviousMediaItemIndex()

Gets the previous item index in the playlist of the SessionPlayer associated with the connected MediaSession. This value would be updated when onCurrentMediaItemChanged or onPlaylistChanged is called.

Interoperability: When connected to android.support.v4.media.session.MediaSessionCompat, this will always return INVALID_ITEM_INDEX.

Returns
int

the index of previous item in playlist, or INVALID_ITEM_INDEX if previous media item does not exist or playlist hasn't been set

getRepeatMode

Added in 1.0.0
Deprecated in 1.3.0
public int getRepeatMode()

Gets the repeat mode of the SessionPlayer associated with the connected MediaSession. If it is not connected yet, it returns REPEAT_MODE_NONE.

Returns
int

repeat mode

getSelectedTrack

Added in 1.1.0
Deprecated in 1.3.0
public @Nullable SessionPlayer.TrackInfo getSelectedTrack(int trackType)

Gets the currently selected track for the given track type of the SessionPlayer associated with the connected MediaSession. If it is not connected yet, it returns null.

The returned value can be outdated after onTracksChanged, onTrackSelected, or onTrackDeselected is called.

Parameters
int trackType

type of selected track

Returns
@Nullable SessionPlayer.TrackInfo

selected track info

getSessionActivity

Added in 1.0.0
Deprecated in 1.3.0
public @Nullable PendingIntent getSessionActivity()

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

Returns
@Nullable PendingIntent

a PendingIntent to launch UI or null

getShuffleMode

Added in 1.0.0
Deprecated in 1.3.0
public int getShuffleMode()

Gets the shuffle mode of the SessionPlayer associated with the connected MediaSession. If it is not connected yet, it returns SHUFFLE_MODE_NONE.

Returns
int

the shuffle mode

getTracks

Added in 1.1.0
Deprecated in 1.3.0
public @NonNull List<SessionPlayer.TrackInfogetTracks()

Gets the full list of selected and unselected tracks that the media contains of the SessionPlayer associated with the connected MediaSession. The order of the list is irrelevant as different players expose tracks in different ways, but the tracks will generally be ordered based on track type.

The types of tracks supported may vary based on player implementation.

Returns
@NonNull List<SessionPlayer.TrackInfo>

list of tracks. The total number of tracks is the size of the list. If empty, an empty list would be returned.

getVideoSize

Added in 1.1.0
Deprecated in 1.3.0
public @NonNull VideoSize getVideoSize()

Gets the video size of the SessionPlayer associated with the connected MediaSession. If it is not connected yet, it returns new VideoSize(0, 0).

Returns
@NonNull VideoSize

the size of the video. The width and height of size could be 0 if there is no video or the size has not been determined yet.