我试图从耳机或汽车控制装置(播放/暂停/等)接收媒体按钮事件。
这是我的应用程序清单。
<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>这是我MediaPlayerService的一部分
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。
你知道为什么这不像预期的那样有效吗?
发布于 2016-07-07 19:42:20
正如在媒体播放I/O 2016 talk的最佳实践中所解释的,您还需要调用
mSession.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);在构造媒体会话时,在开始播放之前,必须按照其文档调用setActive(真):
必须将会话设置为active,然后会话才能开始接收媒体按钮事件或传输命令。
请注意,还必须在调用setActions()上在PlaybackStateCompat.Builder上说明所支持的操作--如果不设置该操作,则不会得到任何与媒体按钮相关的回调。
https://stackoverflow.com/questions/38247050
复制相似问题