问题描述
pre API 21我用像 audioManager.registerMediaButtonEventReceiver(接收器)的呼叫;
来处理媒体按钮事件当用户pressed上的一个按钮他的耳机。由于API 21,似乎 MediaSession
应使用。但是,我没有得到任何回应任何责任。
Pre API 21 I was using a call like audioManager.registerMediaButtonEventReceiver(receiver);
to handle media button events when a user pressed a button on his headset. As of API 21, it seems that MediaSession
should be used. However, I'm not getting any response whatsoever.
final MediaSession session = new MediaSession(context, "TAG");
session.setCallback(new Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
Log.i("TAG", "GOT EVENT");
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
session.setActive(true);
以上是我认为的应该的工作,但没有。有谁知道这是为什么不工作,或者我应该如何注册?
Above is what I think should work but doesn't. Does anyone know why this isn't working or how I should register?
推荐答案
要接收媒体按钮事件,您需要:
To receive media button events, you need to:
-
设置MediaSession.Callback并处理适当的事件(*)
set a MediaSession.Callback and handle the proper events (*)
设置 MediaSession.FLAG_HANDLES_MEDIA_BUTTONS
和 MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS
标志
设置mediaSession为主动
set the mediaSession to active
设置playbackstate正确,在特殊的行动(事件回放),您的会话句柄。例如:
set a playbackstate properly, in special the actions (playback events) that your session handles. For example:
PlaybackState state = new PlaybackState.Builder()
.setActions(
PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_PAUSE |
PlaybackState.ACTION_PLAY_FROM_MEDIA_ID | PlaybackState.ACTION_PAUSE |
PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_SKIP_TO_PREVIOUS)
.setState(PlaybackState.STATE_PLAYING, position, speed, SystemClock.elapsedRealtime())
.build();
mSession.setPlaybackState(state);
我的猜测是,你错过了#4,因为你正在做的一切正常。
My guess is that you are missing #4, because you are doing everything else correctly.
(*)Callback.onMediaButtonEvent的默认实现处理所有常见的多媒体按键,并调用适当的onXXXX()方法(onPlay,在onPause,onSkipToNext等)。除非你需要处理不常见的多媒体按键 - 或调试目的 - ,你不需要重写onMediaButtonEvent
(*) the default implementation of Callback.onMediaButtonEvent handles all common media buttons and calls the proper onXXXX() methods (onPlay, onPause, onSkipToNext, etc). Unless you need to handle uncommon media buttons - or for debugging purposes -, you don't need to override onMediaButtonEvent.
这篇关于在安卓5.0棒棒糖处理多媒体按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!