如何在 Android 8+ 中处理来自 Headest 的媒体按钮

问题描述

在我的应用程序中,我捕获来自耳机的播放事件并覆盖其功能。这适用于 android 6 和 7。在 android 8+ 上,媒体查找过程已更改,它期望应用程序具有正在运行的媒体会话或期望接收器,但我不确定如何使其工作。此 link 描述了更改

在我的清单中,我有服务和接收器:

<!-- The service,that handles media buttons -->
<service android:name=".MediaButtonService">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</service>

<!-- A receiver that will receive media buttons. Required on pre-lollipop devices -->
<receiver android:name="androidx.media.session.MediaButtonReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

在 .MediaButtonService 上,我有以下内容:

private MediaSessionCompat _mediaSession;

@Override
public void onCreate() {
    _mediaSession = new MediaSessionCompat(this,"MediaButtonService");
    _mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    _mediaSession.setPlaybackState(
            new PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY)
            .build());
    _mediaSession.setCallback(new MediaSessionCompat.Callback() {
        @Override
        public void onPlay() {
            Context context = getApplicationContext();
            Intent service = new Intent(context,xxxx.class);
            context.startService(service);
        }
    });
    _mediaSession.setActive(true);
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...