Search code examples
androidkeydownmediasession

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


here's the code to capture any media key events


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);

I used this in a newly created android project, and everything worked good (I could capture key events from foreground and background), however, I used this code in another project and couldn't capture any key events, probably there's something override this or another thing capture key events, how to solve this? I tried to remove (onKeyDown and onKeyUp) functions but still didn't work

Note: I can see this in logcat once I click on the button:

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 }


Solution

  • I found the issue,

    I just have to declare the MediaSession object as a public static, I'm new to android and I don't know why does this solved the issue.