So, after a lot of head scratching, I am at my wit's end. I have a media player RemoteViews
in my notification and I would like to be able to access the play, pause, previous and next buttons.
I know that setOnClickPendingIntent()
will be used to communicate from the notification. However, I am left wondering how that will work.
Is it possible to let the service handle the clicks?
I have tried this, but in vain. I was trying to let me service handle the pause and resume of the player:
rm = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notif_media_player);
Intent intent = new Intent(getApplicationContext(), MusicService.class);
intent.putExtra(REQUEST_CODE, PAUSE);
PendingIntent pending = PendingIntent.getService(getApplicationContext(), PAUSE, intent, 0);
rm.setPendingIntentTemplate(R.id.pause, pending);
Notification notif = new NotificationCompat.Builder(getApplicationContext())
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(rm)
.build();
NotificationManager mgr = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
mgr.notify(NOTIFICATION_ID, notif);
and my IBinder
is null. If that makes a difference.
How do I pause and play music from notification?
Based on CommonsWare
's recommendation:
rm = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notif_media_player);
Intent pauseIntent = new Intent(getApplicationContext(), MusicService.class);
Intent dismissIntent = new Intent(getApplicationContext(), MusicService.class);
pauseIntent.putExtra(REQUEST_CODE, PAUSE);
dismissIntent.putExtra(REQUEST_CODE, DISMISS);
PendingIntent pause = PendingIntent.getService(getApplicationContext(), PAUSE, pauseIntent, 0);
PendingIntent dismiss = PendingIntent.getService(getApplicationContext(), DISMISS, dismissIntent, 0);
rm.setOnClickPendingIntent(R.id.pause, pause);
rm.setOnClickPendingIntent(R.id.dismiss, dismiss);
Notification notif = new NotificationCompat.Builder(getApplicationContext())
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(rm)
.build();
NotificationManager mgr = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
mgr.notify(NOTIFICATION_ID, notif);