这是捕获任何媒体键事件的代码
final MediaSession session = new MediaSession(getApplicationContext(), "TAG");
session.setCallback(new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
Toast.makeText(getApplication(), "key events captured", Toast.LENGTH_LONG).show();
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
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_STOPPED, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 0)
.build();
session.setPlaybackState(state);
session.setActive(true);
我在一个新创建的android项目中使用了它,一切正常(我可以从前台和后台捕获关键事件),但是,我在另一个项目中使用了这个代码并且无法捕获任何关键事件,可能有一些东西覆盖了这个或另一件事捕获关键事件,如何解决这个问题?我试图删除(onKeyDown 和 onKeyUp)功能,但仍然没有工作
注意:单击按钮后,我可以在 logcat 中看到:
07-25 22:08:08.604 688-4294/system_process D/MediaSessionService: dispatchMediaKeyEvent, pid=9965, uid=10070, event=KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_MEDIA_PLAY_PAUSE, scanCode=164, metaState=0, flags=0x8, repeatCount=0, eventTime=2967810, downTime=2967810, deviceId=8, source=0x101 }
07-25 22:08:08.605 688-4294/system_process D/MediaSessionService: Sending media key to com.example.mediabuttons/TAG
07-25 22:08:08.605 9965-9965/com.example.mediabuttons D/MediaSessionHelper: dispatched media key KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_MEDIA_PLAY_PAUSE, scanCode=164, metaState=0, flags=0x8, repeatCount=0, eventTime=2967810, downTime=2967810, deviceId=8, source=0x101 }