Building a Video Player Activity
When the activity receives a callback from the lifecycle onCreate() method it should implement these steps:
Create and initialize a media session
Set callback for media session
Create and initialize a media controller
The sample code steps of onCreate() are as follows:
MediaSessionCompat mMediaSession;
PlaybackStateCompat.Builder mStateBuilder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a MediaSessionCompat
mMediaSession = new MediaSessionCompat(this, LOG_TAG);
// Enable callbacks from MediaButtons and TransportControls
mMediaSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
// Set an initial PlaybackState with ACTION_PLAY, so media buttons can start the player
mStateBuilder = new PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PLAY_PAUSE);
mMediaSession.setState(mStateBuilder.build());
// MySessionCallback has methods that handle callbacks from a media controller
mMediaSession.setCallback(new MySessionCallback());
// Create a MediaControllerCompat
MediaControllerCompat mediaController =
new MediaControllerCompat(this, mMediaSession);
MediaControllerCompat.setMediaController(this, mediaController);
}
When an application is closed, the activity successfully receives onPause() and onStop() callbacks. If the player is playing, you must stop the activity before it leaves. Which callback to choose depends on what Android version you're running on.
On Android 6.0 (API level 23) or earlier, onStop() is not guaranteed to be called, it may be called 5 seconds after your activity disappears. Therefore, before Android 7.0 or earlier, your app should stop playing in onPause(). After Android 7.0, the system calls onStop() as soon as the activity becomes invisible, so this is not a significant issue.
Summarize:
- On Android 6.0 or earlier, stop the player in the onPause() callback.
- On Android 7.0 or higher, stop the player in the onStop() callback.
When the activity receives the onDestroy() callback, it should release and clear the player.