MediaButtonReceiver不能与MediaBrowserServiceCompat一起工作

8

我正在尝试从耳机或汽车控制器(播放/暂停等)接收媒体按钮事件。

这是我的应用程序清单中的内容。

<service android:name=".mediaPlayerService.MediaPlayerService"
         android:exported="true">
    <intent-filter>
        <action android:name="android.media.browse.MediaBrowserService"/>
    </intent-filter>
</service>

<!--
A receiver that will receive media buttons and send as
intents to your MediaBrowserServiceCompat implementation.
Required on pre-Lollipop. More information at
http://developer.android.com/reference/android/support/v4/media/session/MediaButtonReceiver.html
-->
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON"/>
    </intent-filter>
</receiver>

这是我的媒体播放服务的一部分。
public class MediaPlayerService extends MediaBrowserServiceCompat {

@Override
public void onCreate()
{
    super.onCreate();
    initMediaSessions();
}

private void initMediaSessions()
{
    mSession = new MediaSessionCompat(getApplicationContext(), MediaPlayerService.class.getSimpleName());
    setSessionToken(mSession.getSessionToken());

    mSession.setCallback(new MediaSessionCompat.Callback()
                         {
                            //callback code is here.     
                         }            
    );
}

@Override
public int onStartCommand(Intent startIntent, int flags, int startId)
{
    if (startIntent != null)
    {
        // Try to handle the intent as a media button event wrapped by MediaButtonReceiver
        MediaButtonReceiver.handleIntent(mSession, startIntent);
    }
    return START_STICKY;
}

看起来我错过了什么。当我按下耳机控制器上的暂停按钮时,onStartCommand没有被调用。

有任何想法为什么这不像预期的那样工作?

1个回答

13

2016年媒体播放I/O最佳实践讲座中所解释的那样,您还需要调用

mSession.setFlags(
  MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
  MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);

在构建媒体会话并开始播放之前,必须按照其文档调用setActive(true)

在媒体会话开始接收媒体按钮事件或传输命令之前,必须将会话设置为活动状态。

请注意,您还必须在PlaybackStateCompat.Builder调用setActions()以精确说明您支持哪些操作 - 如果不设置,则不会收到与媒体按钮相关的任何回调。

不设置操作听起来很合理。我会再确认一下。 - Hackmodford
我错过了设置操作。标志是自动的,因为我正在使用MediaBrowserCompat。非常感谢! - Hackmodford
我不确定你所说的“Flags were automatic”是什么意思?如果你没有调用setFlags(),那么肯定会出现问题(特别是在<API 21设备上接收媒体按钮时)。 - ianhanniballake
该死的setActions()! - timr
我没有使用 setActive(true),因为他们该死的文档没有提到它。 - Vucko
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接