这个话题有时会弹出,但我不能让那个东西工作。我的应用程序曾经处理媒体按钮,但在 Android 5.0 之后的 API 发生了变化,它需要使这个应用程序适应“捕捉”蓝牙按钮并“以我的方式”处理它们。
我做了很多搜索,发现:
final MediaSession session = new MediaSession(this, "spy tag");
session.setCallback(new MediaSession.Callback() {
@Override
public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
Toast.makeText(me, "on media button event", Toast.LENGTH_SHORT);
Log.i("TAG", "GOT EVENT");
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_PLAYING, 0, 1)
.build();
session.setPlaybackState(state);
session.setActive(true);
但是……还是不行。每当我按下任何媒体按钮时,我都会在 Logcat 中得到这个:
2019-06-16 19:40:14.458 2936-4422/? D/MediaSessionService:发送 KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_MEDIA_NEXT, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=0, downTime=0, deviceId=-1, source=0x0 }到最后已知的 PendingIntent PendingIntent{afe4538: PendingIntentRecord{13648e com.google.android.youtube broadcastIntent}} 2019-06-16 19:40:14.460 3230-3230/? V/Avrcp: recordKeyDispatched: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_MEDIA_NEXT, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=0, downTime=0, deviceId=-1, source=0x0 } 调度到 com.google.android.youtube 2019-06-16 19:40:14.466 2936-4422/? D/MediaSessionService: 发送 KeyEvent { action=ACTION_UP, keyCode=KEYCODE_MEDIA_NEXT, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=0, downTime=0, deviceId=-1, source=0x0 } 到最后一个已知的 PendingIntent PendingIntent{afe4538: PendingIntentRecord{13648e com.google.android.youtube broadcastIntent}} 2019-06-16 19:40:14.475 3230-3230/? V/Avrcp: recordKeyDispatched: KeyEvent { action=ACTION_UP, keyCode=KEYCODE_MEDIA_NEXT, scanCode=0, metaState=0, flags=0x0, repeatCount=0, eventTime=0, downTime=0, deviceId=-1, source=0x0 } 调度到 com.google.android.youtube
我的应用程序没有收到任何回调。我错过了什么?