According to this document:
https://developer.android.com/reference/androidx/media2/widget/VideoView
Using VideoView with SessionPlayer or MediaController
For simple use cases that do not require communication with a MediaSession, apps need to create a player instance that extends SessionPlayer (e.g. MediaPlayer) and link it to this view by calling setPlayer(SessionPlayer).
For more advanced use cases that require a MediaSession (e.g. handling media key events, integrating with other MediaSession apps as Assistant), apps need to create a MediaController that's attached to the MediaSession and link it to this view by calling setMediaController(MediaController).
But there's one very important thing which didn't get noted from this document.
Here's the code snippet about how to use this new VideoView
.
MediaMetadata mediaMetaData = new MediaMetadata.Builder()
.putString(MediaMetadata.METADATA_KEY_TITLE, url)
.build();
UriMediaItem mediaItem = new UriMediaItem.Builder(Uri.parse(url)).build();
mediaItem.setMetadata(mediaMetaData);
MediaPlayer mediaPlayer = new MediaPlayer(getActivity());
mediaPlayer.setMediaItem(mediaItem);
mediaPlayer.prepare();
videoView.setPlayer(mediaPlayer);
You have to call mediaPlayer.prepare()
to tell the MediaPlayer
to start loading.
Otherwise you'll get IllegalStateException
with useless messages.
VideoView#setMediaItem()
method instead, and you can construct an appropriateMediaItem
with theandroidx.media2.UriMediaItem.Builder
class. It has a constructor that takes aContext
and aUri
, and one that takes those along with that headersMap
and aList<HttpCookie>
, both of which are optional (@Nullable
).setVideoUri(Uri, ?)
call with a call tosetMediaItem(MediaItem)
, where theMediaItem
is constructed with anandroidx.media2.UriMediaItem.Builder
.