【发布时间】:2020-07-11 10:54:40
【问题描述】:
我有一个简单的 Android 应用程序,其中包含一个 Activity 和一个派生自 MediaBrowserServiceCompat 的 Service。通过使用MediaBrowserCompat 和MediaControllerCompat,我已成功将其设置为播放我的主要活动中的音频。它甚至可以播放和暂停我的蓝牙耳机的音频。都很好。
我的挑战是出现在锁定屏幕和通知托盘中的NotificationCompat.MediaStyle 通知。通知正确显示。但是,当我使用addAction() 和MediaButtonReceiver.buildMediaButtonPendingIntent 添加按钮时,它们什么都不做。如果我改为添加一个虚拟 PendingIntent 来启动我的主要活动,那效果很好。
这是我生成通知的代码(抱歉,这是在 Xamarin 中运行的 C#,因此大小写和名称将与您的预期略有不同)。这是在我的服务类中。
var builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetVisibility(NotificationCompat.VisibilityPublic)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle("Title")
.SetContentText("Content")
.SetSubText("Subtext")
.SetLargeIcon(icon)
.SetColor(Android.Graphics.Color.DarkOrange)
.SetContentIntent(intent)
.SetDeleteIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(this, PlaybackStateCompat.ActionStop))
.AddAction(new NotificationCompat.Action(
Resource.Drawable.ic_pause, "Pause",
MediaButtonReceiver.BuildMediaButtonPendingIntent(this, PlaybackStateCompat.ActionPause)))
.SetStyle(new Android.Support.V4.Media.App.NotificationCompat.MediaStyle()
.SetShowActionsInCompactView(0)
.SetMediaSession(this.mediaSession.SessionToken)
.SetShowCancelButton(true)
.SetCancelButtonIntent(MediaButtonReceiver.BuildMediaButtonPendingIntent(this, PlaybackStateCompat.ActionStop))
);
this.StartForeground(NOTIFICATION_ID, builder.Build());
这是我目前所看到的试图解决这个问题的方法:
- 当我开始播放时,我使用
MediaSession.setActive(true) - 每次开始和停止播放时,我都会在
PlaybackStateCompat中设置相应的操作 - 我的会话令牌设置正确。
- 我确实没有在我的清单中将任何内容设置为
MediaButtonReceiver,也没有设置任何内容来处理android.intent.action.MEDIA_BUTTON,因为我的目标是Android 5.0 及更高版本并使用@ 987654335@ classes,我的理解是不再需要。
我知道媒体按钮事件已正确路由到我的应用程序,因为我的蓝牙耳机按钮工作。我在我的车上试过,它也在那里工作。 只是通知中的按钮不起作用。我希望它们能够调用MediaSessionCompat.Callback 的适当方法。这是不正确的吗?我在这里做错了什么?
如有任何指点,我将不胜感激。
更新:
我让它工作了。我需要在清单的<application> 节点中添加以下内容:
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
...以及实现MediaBrowserServiceCompat的Service的节点内的以下内容:
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter>
我仍然有点困惑为什么这是必要的,因为我的蓝牙耳机和汽车信息娱乐系统的按钮按下都很好地路由到了应用程序。更重要的是,谷歌says:
如果您的应用中已有
MediaBrowserServiceCompat,MediaButtonReceiver将接收到的关键事件传递给MediaBrowserServiceCompat默认情况下。你可以在你的MediaSessionCompat.Callback.
他们将此作为选项“服务处理 ACTION_MEDIA_BUTTON”的替代方法,所以我认为这意味着我不需要对我的清单做更多的事情。如果有人能在这里启发我,我将不胜感激。
但是,无论如何,这对我有用。
【问题讨论】:
标签: android android-mediasession mediabrowserservicecompat android-notification.mediastyle