Save the date! Android Dev Summit is coming to Sunnyvale, CA on Oct 23-24, 2019.

MediaController2

open class MediaController2 : AutoCloseable
kotlin.Any
   ↳ androidx.media2.MediaController2

Allows an app to interact with an active MediaSession2 or a MediaSessionService2 in any status. Media buttons and other commands can be sent to the session.

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.

When controlling MediaSession2, the controller will be available immediately after the creation.

When controlling MediaSessionService2, the MediaController2 would be available only if the session service allows this controller by MediaSession2.SessionCallback#onConnect(MediaSession2, ControllerInfo) for the service. Wait ControllerCallback#onConnected(MediaController2, SessionCommandGroup2) or ControllerCallback#onDisconnected(MediaController2) for the result.

MediaController2 objects are thread-safe.

Summary

Nested classes
abstract

Interface for listening to change in activeness of the MediaSession2.

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

Public constructors
<init>(@NonNull context: Context, @NonNull token: SessionToken2, @NonNull executor: Executor, @NonNull callback: MediaController2.ControllerCallback)

Create a MediaController2 from the SessionToken2.

Public methods
open MediaItem2!

Get the lastly cached current item from ControllerCallback#onCurrentMediaItemChanged(MediaController2, MediaItem2).

open Long

Gets the duration of the current media item, or MediaPlayerConnector#UNKNOWN_TIME if unknown.

open Unit
updatePlaylistMetadata(@Nullable metadata: MediaMetadata2?)

Updates the playlist metadata

open Unit

Skips to the next item in the playlist.

open Unit
prepareFromSearch(@NonNull query: String, @Nullable extras: Bundle?)

Request that the player prepare playback for a specific search query.

open Unit

Set the playback speed.

open Long

Gets the current playback position.

open MutableList<MediaItem2!>?

Returns the cached playlist from ControllerCallback#onPlaylistChanged.

open Unit

Requests that the player starts or resumes playback.

open Int

Gets the cached shuffle mode from the ControllerCallback#onShuffleModeChanged.

open Unit

Release this object, and disconnect from the session.

open Unit
setRating(@NonNull mediaId: String, @NonNull rating: Rating2)

Rate the media.

open Int

Gets the cached repeat mode from the ControllerCallback#onRepeatModeChanged.

open Int

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

open Unit
setPlaylist(@NonNull list: MutableList<MediaItem2!>, @Nullable metadata: MediaMetadata2?)

Sets the playlist.

open Float

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

open Unit
setShuffleMode(shuffleMode: Int)

Sets the shuffle mode.

open Unit
prepareFromUri(@NonNull uri: Uri, @Nullable extras: Bundle?)

Request that the player prepare playback for a specific Uri.

open Unit
playFromMediaId(@NonNull mediaId: String, @Nullable extras: Bundle?)

Request that the player start playback for a specific media id.

open Unit
playFromUri(@NonNull uri: Uri, @Nullable extras: Bundle?)

Request that the player start playback for a specific Uri.

open Long

Gets the lastly cached buffered position from the session when ControllerCallback#onBufferingStateChanged(MediaController2, MediaItem2, int) is called.

open Unit

Start rewinding.

open Unit
replacePlaylistItem(index: Int, @NonNull item: MediaItem2)

Replace the media item at index in the playlist.

open Unit
addPlaylistItem(index: Int, @NonNull item: MediaItem2)

Adds the media item to the playlist at position index.

open Unit
seekTo(pos: Long)

Move to a new location in the media stream.

open Int

Gets the current buffering state of the player.

open Unit
prepareFromMediaId(@NonNull mediaId: String, @Nullable extras: Bundle?)

Request that the player prepare playback for a specific media id.

open Boolean

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

open Unit

Removes the media item at index in the playlist.

open Unit

Start fast forwarding.

open Unit
setVolumeTo(value: Int, flags: Int)

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

open Unit

Unsubscribes for changes to the routes.

open Unit
setRepeatMode(repeatMode: Int)

Sets the repeat mode.

open Unit
selectRoute(@NonNull route: Bundle)

Selects the specified route.

open Unit

Requests that the player be reset to its uninitialized state.

open Unit

Skips to the item in the playlist.

open MediaController2.PlaybackInfo?

Get the current playback info for this session.

open Unit

Request that the player prepare its playback.

open Unit

Requests that the player pauses playback.

open MediaMetadata2?

Gets the lastly cached playlist playlist metadata either from or

open Unit
adjustVolume(direction: Int, flags: Int)

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

open Unit

Skips to the previous item in the playlist.

open SessionToken2

open PendingIntent?

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

open Unit
sendCustomCommand(@NonNull command: SessionCommand2, @Nullable args: Bundle?, @Nullable cb: ResultReceiver?)

Send custom command to the session

open Unit
playFromSearch(@NonNull query: String, @Nullable extras: Bundle?)

Request that the player start playback for a specific search query.

open Unit

Queries for information about the routes currently known.

Public constructors

<init>

MediaController2(@NonNull context: Context, @NonNull token: SessionToken2, @NonNull executor: Executor, @NonNull callback: MediaController2.ControllerCallback)

Create a MediaController2 from the SessionToken2. This connects to the session and may wake up the service if it's not available.

Parameters
context Context: Context
token Context: token to connect to
executor Context: executor to run callbacks on.
callback Context: controller callback to receive changes in

Public methods

getCurrentMediaItem

open fun getCurrentMediaItem(): MediaItem2!

Get the lastly cached current item from ControllerCallback#onCurrentMediaItemChanged(MediaController2, MediaItem2).

Return
MediaItem2!: the currently playing item, or null if unknown.

getDuration

open fun getDuration(): Long

Gets the duration of the current media item, or MediaPlayerConnector#UNKNOWN_TIME if unknown.

Return
Long: the duration in ms, or MediaPlayerConnector#UNKNOWN_TIME.

updatePlaylistMetadata

open fun updatePlaylistMetadata(@Nullable metadata: MediaMetadata2?): Unit

Updates the playlist metadata

Parameters
metadata MediaMetadata2?: metadata of the playlist

skipToNextItem

open fun skipToNextItem(): Unit

Skips to the next item in the playlist.

This calls MediaPlaylistAgent#skipToNextItem().

prepareFromSearch

open fun prepareFromSearch(@NonNull query: String, @Nullable extras: Bundle?): Unit

Request that the player prepare playback for a specific search query. In other words, other sessions can continue to play during the preparation of this session. This method can be used to speed up the start of the playback. Once the preparation is done, the session will change its playback state to MediaPlayerConnector#PLAYER_STATE_PAUSED. Afterwards, play can be called to start playback. If the preparation is not needed, playFromSearch can be directly called without this method.

Parameters
query String: The search query. Should not be an empty string.
extras String: Optional extras that can include extra information about the query.

setPlaybackSpeed

open fun setPlaybackSpeed(speed: Float): Unit

Set the playback speed.

getCurrentPosition

open fun getCurrentPosition(): Long

Gets the current playback position.

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

Return
Long: position

getPlaylist

@Nullable open fun getPlaylist(): MutableList<MediaItem2!>?

Returns the cached playlist from ControllerCallback#onPlaylistChanged.

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

Return
MutableList<MediaItem2!>?: playlist. Can be null if the playlist hasn't set nor controller doesn't have enough permission.

play

open fun play(): Unit

Requests that the player starts or resumes playback.

getShuffleMode

open fun getShuffleMode(): Int

Gets the cached shuffle mode from the ControllerCallback#onShuffleModeChanged.

Return
Int: The shuffle mode

close

open fun close(): Unit

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

setRating

open fun setRating(@NonNull mediaId: String, @NonNull rating: Rating2): Unit

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 MediaMetadata2#getRating(String) with the key MediaMetadata2#METADATA_KEY_USER_RATING.

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

Parameters
mediaId String: The id of the media
rating String: The rating to set

getPlayerState

open fun getPlayerState(): Int

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

Return
Int: player state

setPlaylist

open fun setPlaylist(@NonNull list: MutableList<MediaItem2!>, @Nullable metadata: MediaMetadata2?): Unit

Sets the playlist.

Even when the playlist is successfully set, use the playlist returned from getPlaylist() for playlist APIs such as skipToPlaylistItem(MediaItem2). Otherwise the session in the remote process can't distinguish between media items.

Parameters
list MutableList<MediaItem2!>: playlist
metadata MutableList<MediaItem2!>: metadata of the playlist

getPlaybackSpeed

open fun getPlaybackSpeed(): Float

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

Return
Float: speed the lastly cached playback speed, or 0.0f if unknown.

setShuffleMode

open fun setShuffleMode(shuffleMode: Int): Unit

Sets the shuffle mode.

Parameters
shuffleMode Int: The shuffle mode

prepareFromUri

open fun prepareFromUri(@NonNull uri: Uri, @Nullable extras: Bundle?): Unit

Request that the player prepare playback for a specific Uri. In other words, other sessions can continue to play during the preparation of this session. This method can be used to speed up the start of the playback. Once the preparation is done, the session will change its playback state to MediaPlayerConnector#PLAYER_STATE_PAUSED. Afterwards, play can be called to start playback. If the preparation is not needed, playFromUri can be directly called without this method.

Parameters
uri Uri: The URI of the requested media.
extras Uri: Optional extras that can include extra information about the media item to be prepared.

playFromMediaId

open fun playFromMediaId(@NonNull mediaId: String, @Nullable extras: Bundle?): Unit

Request that the player start playback for a specific media id.

Parameters
mediaId String: The id of the requested media.
extras String: Optional extras that can include extra information about the media item to be played.

playFromUri

open fun playFromUri(@NonNull uri: Uri, @Nullable extras: Bundle?): Unit

Request that the player start playback for a specific Uri.

Parameters
uri Uri: The URI of the requested media.
extras Uri: Optional extras that can include extra information about the media item to be played.

getBufferedPosition

open fun getBufferedPosition(): Long

Gets the lastly cached buffered position from the session when ControllerCallback#onBufferingStateChanged(MediaController2, MediaItem2, int) is called.

Return
Long: buffering position in millis, or MediaPlayerConnector#UNKNOWN_TIME if unknown.

rewind

open fun rewind(): Unit

Start rewinding. If playback is already rewinding this may increase the rate.

replacePlaylistItem

open fun replacePlaylistItem(index: Int, @NonNull item: MediaItem2): Unit

Replace the media item at index in the playlist. This can be also used to update metadata of an item.

Parameters
index Int: the index of the item to replace
item Int: the new item

addPlaylistItem

open fun addPlaylistItem(index: Int, @NonNull item: MediaItem2): Unit

Adds the media item to the playlist at position index. 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
item Int: the media item you want to add

seekTo

open fun seekTo(pos: Long): Unit

Move to a new location in the media stream.

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

getBufferingState

open fun getBufferingState(): Int

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

Return
Int: the buffering state.

prepareFromMediaId

open fun prepareFromMediaId(@NonNull mediaId: String, @Nullable extras: Bundle?): Unit

Request that the player prepare playback for a specific media id. In other words, other sessions can continue to play during the preparation of this session. This method can be used to speed up the start of the playback. Once the preparation is done, the session will change its playback state to MediaPlayerConnector#PLAYER_STATE_PAUSED. Afterwards, play can be called to start playback. If the preparation is not needed, playFromMediaId can be directly called without this method.

Parameters
mediaId String: The id of the requested media.
extras String: Optional extras that can include extra information about the media item to be prepared.

isConnected

open fun isConnected(): Boolean

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

removePlaylistItem

open fun removePlaylistItem(@NonNull item: MediaItem2): Unit

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
item MediaItem2: the media item you want to add

fastForward

open fun fastForward(): Unit

Start fast forwarding. If playback is already fast forwarding this may increase the rate.

setVolumeTo

open fun setVolumeTo(value: Int, flags: Int): Unit

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

unsubscribeRoutesInfo

open fun unsubscribeRoutesInfo(): Unit

Unsubscribes for changes to the routes.

The callback will no longer be invoked for the routes once this method returns.

setRepeatMode

open fun setRepeatMode(repeatMode: Int): Unit

Sets the repeat mode.

Parameters
repeatMode Int: repeat mode

selectRoute

open fun selectRoute(@NonNull route: Bundle): Unit

Selects the specified route.

Parameters
route Bundle: The route to select.

reset

open fun reset(): Unit

Requests that the player be reset to its uninitialized state.

skipToPlaylistItem

open fun skipToPlaylistItem(@NonNull item: MediaItem2): Unit

Skips to the item in the playlist.

This calls MediaPlaylistAgent#skipToPlaylistItem(MediaItem2).

Parameters
item MediaItem2: The item in the playlist you want to play

getPlaybackInfo

@Nullable open fun getPlaybackInfo(): MediaController2.PlaybackInfo?

Get the current playback info for this session.

Return
MediaController2.PlaybackInfo?: The current playback info or null.

prepare

open fun prepare(): Unit

Request that the player prepare its playback. In other words, other sessions can continue to play during the preparation of this session. This method can be used to speed up the start of the playback. Once the preparation is done, the session will change its playback state to MediaPlayerConnector#PLAYER_STATE_PAUSED. Afterwards, play can be called to start playback.

pause

open fun pause(): Unit

Requests that the player pauses playback.

getPlaylistMetadata

@Nullable open fun getPlaylistMetadata(): MediaMetadata2?

Gets the lastly cached playlist playlist metadata either from or

adjustVolume

open fun adjustVolume(direction: Int, flags: Int): Unit

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

skipToPreviousItem

open fun skipToPreviousItem(): Unit

Skips to the previous item in the playlist.

This calls MediaPlaylistAgent#skipToPreviousItem().

getSessionToken

@NonNull open fun getSessionToken(): SessionToken2
Return
SessionToken2: token

getSessionActivity

@Nullable open fun getSessionActivity(): PendingIntent?

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

Return
PendingIntent?: A PendingIntent to launch UI or null.

sendCustomCommand

open fun sendCustomCommand(@NonNull command: SessionCommand2, @Nullable args: Bundle?, @Nullable cb: ResultReceiver?): Unit

Send custom command to the session

Parameters
command SessionCommand2: custom command
args SessionCommand2: optional argument
cb SessionCommand2: optional result receiver

playFromSearch

open fun playFromSearch(@NonNull query: String, @Nullable extras: Bundle?): Unit

Request that the player start playback for a specific search query.

Parameters
query String: The search query. Should not be an empty string.
extras String: Optional extras that can include extra information about the query.

subscribeRoutesInfo

open fun subscribeRoutesInfo(): Unit

Queries for information about the routes currently known.