Handling media buttons in Android 5.0 Lollipop

前端 未结 1 1615
清歌不尽
清歌不尽 2021-02-07 23:47

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 headse

相关标签:
1条回答
  • 2021-02-08 00:33

    To receive media button events, you need to:

    1. set a MediaSession.Callback and handle the proper events (*)

    2. set MediaSession.FLAG_HANDLES_MEDIA_BUTTONS and MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS flags

    3. set the mediaSession to active

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

    My guess is that you are missing #4, because you are doing everything else correctly.

    (*) 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.

    0 讨论(0)
提交回复
热议问题