I have written complete Music Player to stream music from the web, but I don\'t know how to put media player controls in Notification and when the screen is Lock.
I am f
To achieve this you need media session and notification builber as the following :
private void createMediaSession(){
mediaSessionCompat = new MediaSessionCompat(this, "media session");
stateBuilder = new PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PAUSE |
PlaybackStateCompat.ACTION_PLAY_PAUSE |
PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
);
mediaSessionCompat.setMediaButtonReceiver(null);
mediaSessionCompat.setPlaybackState(stateBuilder.build());
mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
super.onPlay();
//write code to control your music
}
@Override
public void onPause() {
super.onPause();
//write code to control your music
}
@Override
public void onSkipToNext() {
super.onSkipToNext();
//write code to control your music
}
@Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
//write code to control your music
}
});
mediaSessionCompat.setActive(true);
}
private void showNotification(){
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
NotificationCompat.Action playPauseAction = new NotificationCompat.Action(
icon, string,
MediaButtonReceiver.buildMediaButtonPendingIntent(this,
PlaybackStateCompat.ACTION_PLAY_PAUSE)
);
PendingIntent contentPendingIntent = PendingIntent.getActivity(this,
0, new Intent(this, MainActivity.class),0
);
notificationBuilder.setContentTitle("Song Title")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(contentPendingIntent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(playPauseAction)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSessionCompat.getSessionToken())
.setShowActionsInCompactView(0));
notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
finally you need to create a broadcast receiver as the following
public static class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
}
}
and you should add the following dependency in the gradle
implementation 'androidx.media:media:1.1.0'
now you're ready to call the showNotification() method wherever you want to show your notification. If you still having problems you can take a look at this tutorial for your reference