You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Media3:如何为媒体通知添加快进/快退按钮?

问题:Media3自定义媒体通知按钮不生效

我花了整整一周研究这个极其复杂的库,已经黔驴技穷。如今几乎所有主流媒体播放应用都有现成的媒体通知UI方案,包含快进、快退、播放速度及收藏按钮:
主流媒体应用通知UI示例

我严格遵循Android Media3官方背景播放指南操作,但通知毫无变化,当前仅显示上一曲按钮:
当前无效的通知UI

我看过开发者承认该功能实现复杂的相关问题,但无法理解其解决方案。

我未使用PlayerNotificationManager,以下是目前无效的代码实现:

PlaybackService中的代码

private val back = CommandButton.Builder()
        .setEnabled(true)
        .setIconResId(androidx.media3.session.R.drawable.media3_notification_seek_back)
        .setDisplayName("Seek Back")
        .setPlayerCommand(Player.COMMAND_SEEK_BACK)
        .build()
private val forward = CommandButton.Builder()
        .setEnabled(true)
        .setIconResId(androidx.media3.session.R.drawable.media3_notification_seek_forward)
        .setDisplayName("Seek Forward")
        .setPlayerCommand(Player.COMMAND_SEEK_FORWARD)
        .build()
private val buttons = ImmutableList.of(back, forward)

override fun onCreate() {
    super.onCreate()
    val intent = packageManager!!.getLaunchIntentForPackage(packageName)!!
        .let { sessionIntent ->
            PendingIntent.getActivity(this, SESSION_INTENT_REQUEST_CODE, sessionIntent, PendingIntent.FLAG_IMMUTABLE)
        }
    _session = MediaSession.Builder(this, buildPlayer())
        .setSessionActivity(intent)
        .setCustomLayout(buttons)
        .setCallback(CustomMediaSessionCallback())
        .build()
    setListener(PlaybackServiceListener()) // 与当前问题无关
}

private inner class CustomMediaSessionCallback: MediaSession.Callback {
  override fun onConnect(
      session: MediaSession,
      controller: MediaSession.ControllerInfo
  ): MediaSession.ConnectionResult {
      val sessionCommands = MediaSession.ConnectionResult.DEFAULT_PLAYER_COMMANDS.buildUpon()
          .add(back.playerCommand)
          .add(forward.playerCommand)
          .build()
      return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
          .setCustomLayout(buttons)
          .setAvailablePlayerCommands(sessionCommands)
          .build()
  }
}

ViewModel中的代码

private val sessionToken =
        SessionToken(getApplication(), ComponentName(getApplication(), PlaybackService::class.java))
private val controllerFuture = MediaController.Builder(getApplication(), sessionToken).buildAsync()

当MediaController就绪后,我添加MediaItem并开始播放:

with(controller!!) {
    playWhenReady = true
    setMediaItem(mediaItem)
    prepare()
}

需说明的是,即使从MediaSession.Builder中移除.setCustomLayout(buttons)和.setCallback(CustomMediaSessionCallback()),通知也完全无变化。

此外,logcat中出现警告:"Couldn't find a unique registered media button receiver in the given context.",我在Media3仓库中未找到该字符串。

恳请大家帮忙解决,谢谢!


内容的提问来源于stack exchange,提问作者Dale Cooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:59:59