Here is how I did this.
First initialize the MediaSessionCompat, MediaSessionConnector and MediaControllerCompat as given below.
private void initMediaSession(){
ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
mMediaSessionCompat = new MediaSessionCompat(getApplicationContext(), "MyMediasession", mediaButtonReceiver, null);
MediaSessionConnector mediaSessionConnector = new MediaSessionConnector(mMediaSessionCompat, mPlaybackController, false);
mediaSessionConnector.setPlayer(mMediaPlayerManager.getPlayer(), null);
mMediaControllerCompat = mMediaSessionCompat.getController();
}
All the callbacks are received in this MediaSessionConnector.PlaybackController.
private MediaSessionConnector.PlaybackController mPlaybackController = new MediaSessionConnector.PlaybackController() {
@Override
public long getSupportedPlaybackActions(@Nullable Player player) {
long ACTIONS = PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_STOP;
return ACTIONS;
}
@Override
public void onPlay(Player player) {
}
@Override
public void onPause(Player player) {
}
@Override
public void onSeekTo(Player player, long position) {
}
@Override
public void onFastForward(Player player) {
}
@Override
public void onRewind(Player player) {
}
@Override
public void onStop(Player player) {
}
};
Now you can use MediaControllerCompat.TransportControls to send events like play, pause etc. on click of Play/Pause buttons.
mMediaControllerCompat.getTransportControls().play();//For play
mMediaControllerCompat.getTransportControls().pause();//For pause
While using the TransportControls methods corresponding methods of MediaSessionConnector.PlaybackController will also be called simultaneously.