I want to use MediaSession with exoplayer and by searching I found that Exoplayer already have MediaSession extension library(https://github.com/google/ExoPlayer/tree/release-v2/extensions/mediasession), but I am unable to find any good documentation on how to implement that.
I have already read the documentation provided by Google developer on this but it is not clear and hard to understand for me, the documentation link is https://medium.com/google-exoplayer/the-mediasession-extension-for-exoplayer-82b9619deb2d
Can anyone please help me how can I implement MediaSession extension with Exoplayer.
Edited:
Finally I was able to implement this by trying hard using the above link (https://medium.com/google-exoplayer/the-mediasession-extension-for-exoplayer-82b9619deb2d).
Details are given in the answer section below.
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.