Skip to content

Most visited

Recently visited


Building a Video Player Activity

When the activity receives the onCreate() lifecycle callback method it should perform these steps:

The onCreate() code below demonstrates these steps:

MediaSessionCompat mMediaSession;
PlaybackStateCompat.Builder mStateBuilder;

public void onCreate(Bundle savedInstanceState) {

  // Create a MediaSessionCompat
  mMediaSession = new MediaSessionCompat(this, LOG_TAG);

  // Enable callbacks from MediaButtons and TransportControls

  // Do not let MediaButtons restart the player when the app is not visible

  // Set an initial PlaybackState with ACTION_PLAY, so media buttons can start the player
  mStateBuilder = new PlaybackStateCompat.Builder()
                    PlaybackStateCompat.ACTION_PLAY |

  // 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 app is closed, the activity receives the onPause() and onStop() callbacks in succession. If the player is playing, you must stop it before its activity goes away. The choice of which callback to use depends on what Android version you’re running.

In Android 6.0 (API level 23) and earlier there is no guarantee of when onStop() is called; it could get called 5 seconds after your activity disappears. Therefore, in Android versions earlier than 7.0, your app should stop playback in onPause(). In Android 7.0 and beyond, the system calls onStop() as soon as the activity becomes not visible, so this is not a problem.

To summarize:

When the activity receives the onDestroy() callback, it should release and clean up your player.

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields


Follow Google Developers on WeChat

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)