Android 中的媒体控件位于快速设置附近。多个应用的会话排列在一个可滑动的轮播界面中。该轮播界面按以下顺序列出会话:
- 在手机上本地播放的流
- 远程流,例如在外部设备或 Cast 会话中检测到的流
- 之前可恢复的会话,按上次播放的顺序排列
从 Android 13(API 级别 33)开始,为确保用户可以访问用于播放媒体应用的丰富媒体控件,媒体控件上的操作按钮是从 Player
状态派生的。
这样,您就可以在各种设备上呈现一套一致的媒体控件,并提供更完善的媒体控制体验。
图 1 分别展示了其在手机和平板设备上的外观示例。
系统根据 Player
状态显示最多五个操作按钮,具体如以下表格所示。在紧凑模式下,仅显示前三个操作槽。这与媒体控件在其他 Android 平台(如 Auto、Assistant 和 Wear OS)中的呈现方式保持一致。
槽位 | 条件 | 操作 |
---|---|---|
1 |
playWhenReady 为 false 或当前 播放状态 为 STATE_ENDED 。 |
播放 |
playWhenReady 为 true 且当前 播放状态 为 STATE_BUFFERING 。 |
加载微调器 | |
playWhenReady 为 true 且当前 播放状态 为 STATE_READY 。 |
暂停 | |
2 | 媒体按钮偏好设置包含用于 CommandButton.SLOT_BACK 的自定义按钮 |
自定义 |
播放器命令 COMMAND_SEEK_TO_PREVIOUS 或 COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM 可用。 |
上一个 | |
自定义按钮和列出的命令均不可用。 | 空 | |
3 | 媒体按钮偏好设置包含用于 CommandButton.SLOT_FORWARD 的自定义按钮 |
自定义 |
播放器命令 COMMAND_SEEK_TO_NEXT 或 COMMAND_SEEK_TO_NEXT_MEDIA_ITEM 可用。 |
下一个 | |
自定义按钮和列出的命令均不可用。 | 空 | |
4 | 媒体按钮偏好设置包含尚未放置的 CommandButton.SLOT_OVERFLOW 的自定义按钮。 |
自定义 |
5 | 媒体按钮偏好设置包含尚未放置的 CommandButton.SLOT_OVERFLOW 的自定义按钮。 |
自定义 |
自定义溢出按钮按其添加到媒体按钮偏好设置的顺序放置。
自定义命令按钮
如需使用 Jetpack Media3 自定义系统媒体控件,您可以相应地设置会话的媒体按钮偏好设置和控制器的可用命令:
构建
MediaSession
并定义自定义命令按钮的媒体按钮偏好设置。在
MediaSession.Callback.onConnect()
中,通过在ConnectionResult
中定义控制器的可用命令(包括自定义命令)来授权控制器。在
MediaSession.Callback.onCustomCommand()
中,响应用户选择的自定义命令。
Kotlin
class PlaybackService : MediaSessionService() { private val customCommandFavorites = SessionCommand(ACTION_FAVORITES, Bundle.EMPTY) private var mediaSession: MediaSession? = null override fun onCreate() { super.onCreate() val favoriteButton = CommandButton.Builder(CommandButton.ICON_HEART_UNFILLED) .setDisplayName("Save to favorites") .setSessionCommand(customCommandFavorites) .build() val player = ExoPlayer.Builder(this).build() // Build the session with a custom layout. mediaSession = MediaSession.Builder(this, player) .setCallback(MyCallback()) .setMediaButtonPreferences(ImmutableList.of(favoriteButton)) .build() } private inner class MyCallback : MediaSession.Callback { override fun onConnect( session: MediaSession, controller: MediaSession.ControllerInfo ): ConnectionResult { // Set available player and session commands. return AcceptedResultBuilder(session) .setAvailableSessionCommands( ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon() .add(customCommandFavorites) .build() ) .build() } override fun onCustomCommand( session: MediaSession, controller: MediaSession.ControllerInfo, customCommand: SessionCommand, args: Bundle ): ListenableFuture{ if (customCommand.customAction == ACTION_FAVORITES) { // Do custom logic here saveToFavorites(session.player.currentMediaItem) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) } return super.onCustomCommand(session, controller, customCommand, args) } } }
Java
public class PlaybackService extends MediaSessionService { private static final SessionCommand CUSTOM_COMMAND_FAVORITES = new SessionCommand("ACTION_FAVORITES", Bundle.EMPTY); @Nullable private MediaSession mediaSession; public void onCreate() { super.onCreate(); CommandButton favoriteButton = new CommandButton.Builder(CommandButton.ICON_HEART_UNFILLED) .setDisplayName("Save to favorites") .setSessionCommand(CUSTOM_COMMAND_FAVORITES) .build(); Player player = new ExoPlayer.Builder(this).build(); // Build the session with a custom layout. mediaSession = new MediaSession.Builder(this, player) .setCallback(new MyCallback()) .setMediaButtonPreferences(ImmutableList.of(favoriteButton)) .build(); } private static class MyCallback implements MediaSession.Callback { @Override public ConnectionResult onConnect( MediaSession session, MediaSession.ControllerInfo controller) { // Set available player and session commands. return new AcceptedResultBuilder(session) .setAvailableSessionCommands( ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon() .add(CUSTOM_COMMAND_FAVORITES) .build()) .build(); } public ListenableFutureonCustomCommand( MediaSession session, MediaSession.ControllerInfo controller, SessionCommand customCommand, Bundle args) { if (customCommand.customAction.equals(CUSTOM_COMMAND_FAVORITES.customAction)) { // Do custom logic here saveToFavorites(session.getPlayer().getCurrentMediaItem()); return Futures.immediateFuture(new SessionResult(SessionResult.RESULT_SUCCESS)); } return MediaSession.Callback.super.onCustomCommand( session, controller, customCommand, args); } } }
如需详细了解如何配置 MediaSession
,以便系统等客户端能够连接到您的媒体应用,请参阅向其他客户端授予控制权。
借助 Jetpack Media3,当您实现 MediaSession
时,您的 PlaybackState
会自动与媒体播放器保持同步。同样,当您实现 MediaSessionService
时,该库会自动为您发布 MediaStyle
通知并使其保持最新。
响应操作按钮
当用户点按系统媒体控件中的操作按钮时,系统的 MediaController
会向您的 MediaSession
发送播放命令。MediaSession
随后会将这些命令委托给播放器。Media3 的 Player
接口中定义的命令由媒体会话自动处理。
有关如何响应自定义命令的指导,请参阅添加自定义命令。
支持媒体恢复
媒体恢复功能允许用户直接从轮播界面重新开始之前的会话,而无需启动应用。播放开始后,用户可以通过常规方式与媒体控件互动。
可以使用“设置”应用中的 声音 > 媒体 选项来开启和关闭播放恢复功能。用户还可以通过点按展开的轮播界面上出现的齿轮图标来访问“设置”。
Media3 提供了 API,可以更轻松地支持媒体恢复。有关实现此功能的指导,请参阅Media3 播放恢复文档。
使用旧版媒体 API
本部分介绍如何使用旧版 MediaCompat API 与系统媒体控件集成。
系统从 MediaSession
的 MediaMetadata
中检索以下信息,并在可用时显示:
METADATA_KEY_ALBUM_ART_URI
METADATA_KEY_TITLE
METADATA_KEY_DISPLAY_TITLE
METADATA_KEY_ARTIST
METADATA_KEY_DURATION
(如果未设置时长,则进度条不显示进度)
为确保您拥有有效且准确的媒体控制通知,请将 METADATA_KEY_TITLE
或 METADATA_KEY_DISPLAY_TITLE
元数据的值设置为当前播放媒体的标题。
媒体播放器会显示当前播放媒体的已用时间以及一个与 MediaSession
PlaybackState
映射的进度条。
媒体播放器会显示当前播放媒体的进度,以及一个与 MediaSession
PlaybackState
映射的进度条。进度条允许用户更改位置并显示媒体项的已用时间。要启用进度条,您必须实现 PlaybackState.Builder#setActions
并包含 ACTION_SEEK_TO
。
槽位 | 操作 | 条件 |
---|---|---|
1 | 播放 | 以下是 PlaybackState 的当前状态之一:
|
加载微调器 | 以下是 PlaybackState 的当前状态之一:
|
|
暂停 | PlaybackState 的当前状态不是上述任何一种。 |
|
2 | 上一个 | PlaybackState 操作包括 ACTION_SKIP_TO_PREVIOUS 。 |
自定义 | PlaybackState 操作不包括 ACTION_SKIP_TO_PREVIOUS ,并且 PlaybackState 自定义操作包含尚未放置的自定义操作。 |
|
空 | PlaybackState 额外数据包括键 SESSION_EXTRAS_KEY_SLOT_RESERVATION_SKIP_TO_PREV 的 true 布尔值。 |
|
3 | 下一个 | PlaybackState 操作包括 ACTION_SKIP_TO_NEXT 。 |
自定义 | PlaybackState 操作不包括 ACTION_SKIP_TO_NEXT ,并且 PlaybackState 自定义操作包含尚未放置的自定义操作。 |
|
空 | PlaybackState 额外数据包括键 SESSION_EXTRAS_KEY_SLOT_RESERVATION_SKIP_TO_NEXT 的 true 布尔值。 |
|
4 | 自定义 | PlaybackState 自定义操作包含尚未放置的自定义操作。 |
5 | 自定义 | PlaybackState 自定义操作包含尚未放置的自定义操作。 |
添加标准操作
以下代码示例演示了如何添加 PlaybackState
标准操作和自定义操作。
对于播放、暂停、上一个和下一个,请在媒体会话的 PlaybackState
中设置这些操作。
Kotlin
val session = MediaSessionCompat(context, TAG) val playbackStateBuilder = PlaybackStateCompat.Builder() val style = NotificationCompat.MediaStyle() // For this example, the media is currently paused: val state = PlaybackStateCompat.STATE_PAUSED val position = 0L val playbackSpeed = 1f playbackStateBuilder.setState(state, position, playbackSpeed) // And the user can play, skip to next or previous, and seek val stateActions = PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SEEK_TO // adding the seek action enables seeking with the seekbar playbackStateBuilder.setActions(stateActions) // ... do more setup here ... session.setPlaybackState(playbackStateBuilder.build()) style.setMediaSession(session.sessionToken) notificationBuilder.setStyle(style)
Java
MediaSessionCompat session = new MediaSessionCompat(context, TAG); PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder(); NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle(); // For this example, the media is currently paused: int state = PlaybackStateCompat.STATE_PAUSED; long position = 0L; float playbackSpeed = 1f; playbackStateBuilder.setState(state, position, playbackSpeed); // And the user can play, skip to next or previous, and seek long stateActions = PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SEEK_TO; // adding this enables the seekbar thumb playbackStateBuilder.setActions(stateActions); // ... do more setup here ... session.setPlaybackState(playbackStateBuilder.build()); style.setMediaSession(session.getSessionToken()); notificationBuilder.setStyle(style);
如果您不希望在上一个或下一个槽位中显示任何按钮,请不要添加 ACTION_SKIP_TO_PREVIOUS
或 ACTION_SKIP_TO_NEXT
,而是向会话添加额外数据。
Kotlin
session.setExtras(Bundle().apply { putBoolean(SESSION_EXTRAS_KEY_SLOT_RESERVATION_SKIP_TO_PREV, true) putBoolean(SESSION_EXTRAS_KEY_SLOT_RESERVATION_SKIP_TO_NEXT, true) })
Java
Bundle extras = new Bundle(); extras.putBoolean(SESSION_EXTRAS_KEY_SLOT_RESERVATION_SKIP_TO_PREV, true); extras.putBoolean(SESSION_EXTRAS_KEY_SLOT_RESERVATION_SKIP_TO_NEXT, true); session.setExtras(extras);
添加自定义操作
对于您想在媒体控件上显示的其他操作,您可以创建一个 PlaybackStateCompat.CustomAction
并将其添加到 PlaybackState
中。这些操作将按照添加的顺序显示。
Kotlin
val customAction = PlaybackStateCompat.CustomAction.Builder( "com.example.MY_CUSTOM_ACTION", // action ID "Custom Action", // title - used as content description for the button R.drawable.ic_custom_action ).build() playbackStateBuilder.addCustomAction(customAction)
Java
PlaybackStateCompat.CustomAction customAction = new PlaybackStateCompat.CustomAction.Builder( "com.example.MY_CUSTOM_ACTION", // action ID "Custom Action", // title - used as content description for the button R.drawable.ic_custom_action ).build(); playbackStateBuilder.addCustomAction(customAction);
响应 PlaybackState 操作
当用户点按按钮时,SystemUI 会使用 MediaController.TransportControls
将命令发送回 MediaSession
。您需要注册一个回调,以便正确响应这些事件。
Kotlin
val callback = object: MediaSession.Callback() { override fun onPlay() { // start playback } override fun onPause() { // pause playback } override fun onSkipToPrevious() { // skip to previous } override fun onSkipToNext() { // skip to next } override fun onSeekTo(pos: Long) { // jump to position in track } override fun onCustomAction(action: String, extras: Bundle?) { when (action) { CUSTOM_ACTION_1 -> doCustomAction1(extras) CUSTOM_ACTION_2 -> doCustomAction2(extras) else -> { Log.w(TAG, "Unknown custom action $action") } } } } session.setCallback(callback)
Java
MediaSession.Callback callback = new MediaSession.Callback() { @Override public void onPlay() { // start playback } @Override public void onPause() { // pause playback } @Override public void onSkipToPrevious() { // skip to previous } @Override public void onSkipToNext() { // skip to next } @Override public void onSeekTo(long pos) { // jump to position in track } @Override public void onCustomAction(String action, Bundle extras) { if (action.equals(CUSTOM_ACTION_1)) { doCustomAction1(extras); } else if (action.equals(CUSTOM_ACTION_2)) { doCustomAction2(extras); } else { Log.w(TAG, "Unknown custom action " + action); } } };
媒体恢复
要使您的播放器应用显示在快速设置区域,您必须创建一个带有有效 MediaSession
令牌的 MediaStyle
通知。
要显示 MediaStyle 通知的标题,请使用 NotificationBuilder.setContentTitle()
。
要显示媒体播放器的品牌图标,请使用 NotificationBuilder.setSmallIcon()
。
为支持播放恢复,应用必须实现 MediaBrowserService
和 MediaSession
。您的 MediaSession
必须实现 onPlay()
回调。
MediaBrowserService
实现
设备启动后,系统会查找最近使用的五个媒体应用,并提供可用于从每个应用重新开始播放的控件。
系统会尝试通过 SystemUI 的连接来联系您的 MediaBrowserService
。您的应用必须允许此类连接,否则将无法支持播放恢复。
来自 SystemUI 的连接可以使用软件包名称 com.android.systemui
和签名进行识别和验证。SystemUI 使用平台签名进行签名。有关如何对照平台签名进行检查的示例,请参阅 UAMP 应用。
为了支持播放恢复,您的 MediaBrowserService
必须实现以下行为:
onGetRoot()
必须快速返回一个非 null 的根。其他复杂逻辑应在onLoadChildren()
中处理。当对根媒体 ID 调用
onLoadChildren()
时,结果必须包含一个 FLAG_PLAYABLE 子项。MediaBrowserService
在收到 EXTRA_RECENT 查询时,应返回最近播放的媒体项。返回的值应是实际的媒体项,而非通用函数。MediaBrowserService
必须提供一个适当的 MediaDescription,其中包含非空的标题和副标题。它还应设置图标 URI 或图标位图。
以下代码示例演示了如何实现 onGetRoot()
。
Kotlin
override fun onGetRoot( clientPackageName: String, clientUid: Int, rootHints: Bundle? ): BrowserRoot? { ... // Verify that the specified package is SystemUI. You'll need to write your // own logic to do this. if (isSystem(clientPackageName, clientUid)) { rootHints?.let { if (it.getBoolean(BrowserRoot.EXTRA_RECENT)) { // Return a tree with a single playable media item for resumption. val extras = Bundle().apply { putBoolean(BrowserRoot.EXTRA_RECENT, true) } return BrowserRoot(MY_RECENTS_ROOT_ID, extras) } } // You can return your normal tree if the EXTRA_RECENT flag is not present. return BrowserRoot(MY_MEDIA_ROOT_ID, null) } // Return an empty tree to disallow browsing. return BrowserRoot(MY_EMPTY_ROOT_ID, null)
Java
@Override public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) { ... // Verify that the specified package is SystemUI. You'll need to write your // own logic to do this. if (isSystem(clientPackageName, clientUid)) { if (rootHints != null) { if (rootHints.getBoolean(BrowserRoot.EXTRA_RECENT)) { // Return a tree with a single playable media item for resumption. Bundle extras = new Bundle(); extras.putBoolean(BrowserRoot.EXTRA_RECENT, true); return new BrowserRoot(MY_RECENTS_ROOT_ID, extras); } } // You can return your normal tree if the EXTRA_RECENT flag is not present. return new BrowserRoot(MY_MEDIA_ROOT_ID, null); } // Return an empty tree to disallow browsing. return new BrowserRoot(MY_EMPTY_ROOT_ID, null); }
Android 13 之前的行为
为了向后兼容,对于未更新以定位 Android 13 或未包含 PlaybackState
信息的应用,System UI 继续提供使用通知操作的备用布局。操作按钮派生自附加到 MediaStyle
通知中的 Notification.Action
列表。系统最多按添加顺序显示五个操作。在紧凑模式下,最多显示三个按钮,其数量由传递给 setShowActionsInCompactView()
的值决定。
自定义操作按照添加到 PlaybackState
的顺序放置。
以下代码示例演示了如何将操作添加到 MediaStyle 通知:
Kotlin
import androidx.core.app.NotificationCompat import androidx.media3.session.MediaStyleNotificationHelper var notification = NotificationCompat.Builder(context, CHANNEL_ID) // Show controls on lock screen even when user hides sensitive content. .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setSmallIcon(R.drawable.ic_stat_player) // Add media control buttons that invoke intents in your media service .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) // #0 .addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) // #1 .addAction(R.drawable.ic_next, "Next", nextPendingIntent) // #2 // Apply the media style template .setStyle(MediaStyleNotificationHelper.MediaStyle(mediaSession) .setShowActionsInCompactView(1 /* #1: pause button */)) .setContentTitle("Wonderful music") .setContentText("My Awesome Band") .setLargeIcon(albumArtBitmap) .build()
Java
import androidx.core.app.NotificationCompat; import androidx.media3.session.MediaStyleNotificationHelper; NotificationCompat.Builder notification = new NotificationCompat.Builder(context, CHANNEL_ID) // Show controls on lock screen even when user hides sensitive content. .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setSmallIcon(R.drawable.ic_stat_player) // Add media control buttons that invoke intents in your media service .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) // #0 .addAction(R.drawable.ic_pause, "Pause", pausePendingIntent) // #1 .addAction(R.drawable.ic_next, "Next", nextPendingIntent) // #2 // Apply the media style template .setStyle(new MediaStyleNotificationHelper.MediaStyle(mediaSession) .setShowActionsInCompactView(1 /* #1: pause button */)) .setContentTitle("Wonderful music") .setContentText("My Awesome Band") .setLargeIcon(albumArtBitmap) .build();