我正在尝试使用新的MediaSession类接收媒体按钮按下,到目前为止,我一直没有成功.有没有人设法使用新课程接收它们?
我已成功创建MediaSession并使用它来更新远程显示器(车载娱乐系统)上的歌曲信息,但到目前为止我无法接收按钮,耳机控制和蓝牙耳机控件.
在我创建媒体会话后,我在用于播放音频的服务中执行以下操作:
_mediaSession = new MediaSession(getApplicationContext(), Global.PACKAGE_NAME + "." + TAG);
if (_mediaSession == null) {
_log.e(TAG, "initMediaSession: _mediaSession = null");
return;
}
_mediaSessionToken = _mediaSession.getSessionToken();
_mediaSession.setCallback(new Callback() {
public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
_log.d(TAG, "onMediaButtonEvent called: " + mediaButtonIntent);
return false;
}
public void onPause() {
Log.d(TAG, "onPause called (media button pressed)");
super.onPause();
}
public void onPlay() {
Log.d(TAG, "onPlay called (media button pressed)");
super.onPlay();
}
public void onStop() {
Log.d(TAG, "onStop called (media button pressed)");
super.onStop();
}
});
_mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
PlaybackState state = new PlaybackState.Builder()
.setActions(PlaybackState.ACTION_PLAY)
.setState(PlaybackState.STATE_STOPPED, PlaybackState.PLAYBACK_POSITION_UNKNowN, SystemClock.elapsedRealtime())
.build();
_mediaSession.setPlaybackState(state);
_mediaSession.setActive(true);
但我仍然没有接到任何按钮按下.
有人有想法么?
谢谢
更新后更新
PlaybackState state = new PlaybackState.Builder()
.setActions(PlaybackState.ACTION_PLAY)
.setState(PlaybackState.STATE_STOPPED, PlaybackState.PLAYBACK_POSITION_UNKNowN, SystemClock.elapsedRealtime())
.build();
至
PlaybackState state = new PlaybackState.Builder()
.setActions(PlaybackState.ACTION_PLAY)
.setState(PlaybackState.STATE_STOPPED, PlaybackState.PLAYBACK_POSITION_UNKNowN, 0)
.build();
我现在通过onMediaButtonEvent()回调接收按钮按下通知(例如被通知按下KEYCODE_MEDIA_PAUSE)但是onPlay(),onPause()和onStop()从未被调用,任何想法为什么?
解决方法:
onMediaButtonEvent(..)在MediaSession.Callback中有一个默认实现.在您的代码中,如果您调用super.onMediaButtonEvent(..),那么根据键代码的正确回调即onPlay(),将调用onPause().
您可以查看MediaSession.java中的默认实现