Android - MediaSession 不捕获关键事件,但是在 logcat 中看到

Android - MediaSession doesn't capture key events however seen in logcat

这是捕获任何媒体键事件的代码


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 }

我发现了问题,

我只需要将 MediaSession 对象声明为 public 静态对象,我是 android 的新手,我不知道为什么这样可以解决问题。