直接前往內容

最常造訪的網頁

最近瀏覽的網頁

navigation

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;

@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);

  // Do not let MediaButtons restart the player when the app is not visible
  mMediaSession.setMediaButtonReceiver(null);

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

本網站使用 Cookie 儲存你在此指定的語言和顯示選項偏好設定。

掌握有關 Android 開發人員的最新消息和實用訣竅,協助你製作最受歡迎的 Google Play 內容。

* 必填欄位

訂閱成功!

在 WeChat 上追蹤 Google Developers

你要以瀏覽這個網站嗎?

你要求以顯示這個網頁,但你為此網站指定的語言偏好設定為

是否要變更語言偏好設定並改用瀏覽網站?稍後如要變更語言偏好設定,請利用位在每個網頁最下方的語言選單來調整設定。

你的 API 層級必須達 以上才能存取這個級別

本說明文件已隱藏,因為你為該文件選取的 API 層級為 。使用左側導覽列上方的選取工具即可變更說明文件的 API 層級。

如需進一步瞭解如何為應用程式指定 API 層級的相關資訊,請參閱 Supporting Different Platform Versions (支援不同的平台版本) (英文)。

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