I have a music player which shows a media notification while audio is playing. I want the user to be able to dismiss the notification when music is paused.
I have to use startForeground so that the service will continue running AND it will stay attached to the activity. I've tried using a notification channel, once I kill the activity playback stops as well which isn't what I want (the code is still in there, commented out).
When the notification is shown, I call startForeground. setOngoing is set to playbackState == STATE_PLAYING. I call stopForeground when the service is destroyed or when playbackState == null || STOPPED.
Pastebin: https://pastebin.com/FNTSSzjS
Code snippet (because you need to include code with pastebin)
private void addPlayPauseAction(NotificationCompat.Builder builder) {
String label;
int icon;
PendingIntent intent;
if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
label = service.getString(R.string.play_pause);
icon = android.R.drawable.ic_media_pause;
intent = intentPause;
builder.setOngoing(true);
} else {
label = service.getString(R.string.play_pause);
icon = android.R.drawable.ic_media_play;
intent = intentPlay;
builder.setOngoing(false);
}
builder.addAction(new NotificationCompat.Action(icon, label, intent));
}
relevant methods in PasteBin are startNotification, stopNotification, createNotification, addPlayPauseAction, and setNotificationPlaybackState