Save the date! Android Dev Summit is coming to Mountain View, CA on November 7-8, 2018.

belongs to Maven artifact androidx.media2:media2:1.0.0-alpha03

MediaController2

public class MediaController2
extends Object implements AutoCloseable

java.lang.Object
   ↳ 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 MediaController2.ControllerCallback.onConnected(MediaController2, SessionCommandGroup2) or MediaController2.ControllerCallback.onDisconnected(MediaController2) for the result.

MediaController2 objects are thread-safe.

Summary

Nested classes

class MediaController2.ControllerCallback

Interface for listening to change in activeness of the MediaSession2

class MediaController2.PlaybackInfo

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

Public constructors

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

Create a MediaController2 from the SessionToken2.

Public methods

void addPlaylistItem(int index, MediaItem2 item)

Adds the media item to the playlist at position index.

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

void fastForward()

Start fast forwarding.

long getBufferedPosition()

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

int getBufferingState()

Gets the current buffering state of the player.

MediaItem2 getCurrentMediaItem()

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

long getCurrentPosition()

Gets the current playback position.

long getDuration()

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

MediaController2.PlaybackInfo getPlaybackInfo()

Get the current playback info for this session.

float getPlaybackSpeed()

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

int getPlayerState()

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

List<MediaItem2> getPlaylist()

Returns the cached playlist from MediaController2.ControllerCallback.onPlaylistChanged(MediaController2, List, MediaMetadata2).

MediaMetadata2 getPlaylistMetadata()

Gets the lastly cached playlist playlist metadata either from {@link ControllerCallback#onPlaylistMetadataChanged or {@link ControllerCallback#onPlaylistChanged}.

int getRepeatMode()

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

PendingIntent getSessionActivity()

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

SessionToken2 getSessionToken()
int getShuffleMode()

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

boolean isConnected()

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

void pause()

Requests that the player pauses playback.

void play()

Requests that the player starts or resumes playback.

void playFromMediaId(String mediaId, Bundle extras)

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

void playFromSearch(String query, Bundle extras)

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

void playFromUri(Uri uri, Bundle extras)

Request that the player start playback for a specific Uri.

void prepare()

Request that the player prepare its playback.

void prepareFromMediaId(String mediaId, Bundle extras)

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

void prepareFromSearch(String query, Bundle extras)

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

void prepareFromUri(Uri uri, Bundle extras)

Request that the player prepare playback for a specific Uri.

void removePlaylistItem(MediaItem2 item)

Removes the media item at index in the playlist.

void replacePlaylistItem(int index, MediaItem2 item)

Replace the media item at index in the playlist.

void reset()

Requests that the player be reset to its uninitialized state.

void rewind()

Start rewinding.

void seekTo(long pos)

Move to a new location in the media stream.

void selectRoute(Bundle route)

Selects the specified route.

void sendCustomCommand(SessionCommand2 command, Bundle args, ResultReceiver cb)

Send custom command to the session

void setPlaybackSpeed(float speed)

Set the playback speed.

void setPlaylist(List<MediaItem2> list, MediaMetadata2 metadata)

Sets the playlist.

void setRating(String mediaId, Rating2 rating)

Rate the media.

void setRepeatMode(int repeatMode)

Sets the repeat mode.

void setShuffleMode(int shuffleMode)

Sets the shuffle mode.

void setVolumeTo(int value, int flags)

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

void skipToNextItem()

Skips to the next item in the playlist.

void skipToPlaylistItem(MediaItem2 item)

Skips to the item in the playlist.

void skipToPreviousItem()

Skips to the previous item in the playlist.

void subscribeRoutesInfo()

Queries for information about the routes currently known.

void unsubscribeRoutesInfo()

Unsubscribes for changes to the routes.

void updatePlaylistMetadata(MediaMetadata2 metadata)

Updates the playlist metadata

Inherited methods

Public constructors

MediaController2

public MediaController2 (Context context, 
                SessionToken2 token, 
                Executor executor, 
                MediaController2.ControllerCallback callback)

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 SessionToken2: token to connect to

executor Executor: executor to run callbacks on.

callback MediaController2.ControllerCallback: controller callback to receive changes in

Public methods

addPlaylistItem

public void addPlaylistItem (int index, 
                MediaItem2 item)

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

adjustVolume

public void 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

See also:

close

public void close ()

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

fastForward

public void fastForward ()

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

getBufferedPosition

public long getBufferedPosition ()

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

Returns
long buffering position in millis, or MediaPlayerConnector.UNKNOWN_TIME if unknown.

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.

getCurrentMediaItem

public MediaItem2 getCurrentMediaItem ()

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

Returns
MediaItem2 the currently playing item, or null if unknown.

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 position

getDuration

public long getDuration ()

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

Returns
long the duration in ms, or MediaPlayerConnector.UNKNOWN_TIME.

getPlaybackInfo

public MediaController2.PlaybackInfo getPlaybackInfo ()

Get the current playback info for this session.

Returns
MediaController2.PlaybackInfo The current playback info or null.

getPlaybackSpeed

public float getPlaybackSpeed ()

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

Returns
float speed the lastly cached playback speed, or 0.0f if unknown.

getPlayerState

public int getPlayerState ()

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

Returns
int player state

getPlaylist

public List<MediaItem2> getPlaylist ()

Returns the cached playlist from MediaController2.ControllerCallback.onPlaylistChanged(MediaController2, List, MediaMetadata2).

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

Returns
List<MediaItem2> playlist. Can be null if the playlist hasn't set nor controller doesn't have enough permission.

getPlaylistMetadata

public MediaMetadata2 getPlaylistMetadata ()

Gets the lastly cached playlist playlist metadata either from {@link ControllerCallback#onPlaylistMetadataChanged or {@link ControllerCallback#onPlaylistChanged}.

Returns
MediaMetadata2 metadata metadata of the playlist, or null if none is set

getSessionActivity

public PendingIntent getSessionActivity ()

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

Returns
PendingIntent A PendingIntent to launch UI or null.

getSessionToken

public SessionToken2 getSessionToken ()

Returns
SessionToken2 token

getShuffleMode

public int getShuffleMode ()

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

Returns
int The shuffle mode

isConnected

public boolean isConnected ()

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

Returns
boolean

pause

public void pause ()

Requests that the player pauses playback.

play

public void play ()

Requests that the player starts or resumes playback.

playFromMediaId

public void playFromMediaId (String mediaId, 
                Bundle extras)

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

Parameters
mediaId String: The id of the requested media.

extras Bundle: Optional extras that can include extra information about the media item to be played.

playFromSearch

public void playFromSearch (String query, 
                Bundle extras)

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

Parameters
query String: The search query. Should not be an empty string.

extras Bundle: Optional extras that can include extra information about the query.

playFromUri

public void playFromUri (Uri uri, 
                Bundle extras)

Request that the player start playback for a specific Uri.

Parameters
uri Uri: The URI of the requested media.

extras Bundle: Optional extras that can include extra information about the media item to be played.

prepare

public void prepare ()

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.

prepareFromMediaId

public void prepareFromMediaId (String mediaId, 
                Bundle extras)

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(String, Bundle) can be directly called without this method.

Parameters
mediaId String: The id of the requested media.

extras Bundle: Optional extras that can include extra information about the media item to be prepared.

prepareFromSearch

public void prepareFromSearch (String query, 
                Bundle extras)

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(String, Bundle) can be directly called without this method.

Parameters
query String: The search query. Should not be an empty string.

extras Bundle: Optional extras that can include extra information about the query.

prepareFromUri

public void prepareFromUri (Uri uri, 
                Bundle extras)

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(Uri, Bundle) can be directly called without this method.

Parameters
uri Uri: The URI of the requested media.

extras Bundle: Optional extras that can include extra information about the media item to be prepared.

removePlaylistItem

public void removePlaylistItem (MediaItem2 item)

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

replacePlaylistItem

public void replacePlaylistItem (int index, 
                MediaItem2 item)

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 MediaItem2: the new item

reset

public void reset ()

Requests that the player be reset to its uninitialized state.

rewind

public void rewind ()

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

seekTo

public void seekTo (long pos)

Move to a new location in the media stream.

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

selectRoute

public void selectRoute (Bundle route)

Selects the specified route.

Parameters
route Bundle: The route to select.

sendCustomCommand

public void sendCustomCommand (SessionCommand2 command, 
                Bundle args, 
                ResultReceiver cb)

Send custom command to the session

Parameters
command SessionCommand2: custom command

args Bundle: optional argument

cb ResultReceiver: optional result receiver

setPlaybackSpeed

public void setPlaybackSpeed (float speed)

Set the playback speed.

Parameters
speed float

setPlaylist

public void setPlaylist (List<MediaItem2> list, 
                MediaMetadata2 metadata)

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 List: playlist

metadata MediaMetadata2: metadata of the playlist

setRating

public void setRating (String mediaId, 
                Rating2 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 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 Rating2: The rating to set

setRepeatMode

public void setRepeatMode (int repeatMode)

Sets the repeat mode.

Parameters
repeatMode int: repeat mode

setShuffleMode

public void setShuffleMode (int shuffleMode)

Sets the shuffle mode.

Parameters
shuffleMode int: The shuffle mode

setVolumeTo

public void 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

See also:

skipToNextItem

public void skipToNextItem ()

Skips to the next item in the playlist.

This calls MediaPlaylistAgent.skipToNextItem().

skipToPlaylistItem

public void skipToPlaylistItem (MediaItem2 item)

Skips to the item in the playlist.

This calls MediaPlaylistAgent.skipToPlaylistItem(MediaItem2).

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

skipToPreviousItem

public void skipToPreviousItem ()

Skips to the previous item in the playlist.

This calls MediaPlaylistAgent.skipToPreviousItem().

subscribeRoutesInfo

public void subscribeRoutesInfo ()

Queries for information about the routes currently known.

unsubscribeRoutesInfo

public void unsubscribeRoutesInfo ()

Unsubscribes for changes to the routes.

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

updatePlaylistMetadata

public void updatePlaylistMetadata (MediaMetadata2 metadata)

Updates the playlist metadata

Parameters
metadata MediaMetadata2: metadata of the playlist