I have an app that has an ongoing notification to help with memorization. I want to be able to dismiss this notification with one of the action button, but I don\'t want to
Start with this:
int final NOTIFICATION_ID = 1;
//Create an Intent for the BroadcastReceiver
Intent buttonIntent = new Intent(context, ButtonReceiver.class);
buttonIntent.putExtra("notificationId",NOTIFICATION_ID);
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent,0);
//Pass this PendingIntent to addAction method of Intent Builder
NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
.....
.....
.....
mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
manager.notify(NOTIFICATION_ID, mb.build());
Create the BroadcastReceiver:
public class ButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
// Do what you want were.
..............
..............
// if you want cancel notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
If you don´t want show any activity when user click on notification, define the intent passed in setContentIntent
in this way:
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
......
......
mb.setContentIntent(resultPendingIntent);
To close notification tray when clicked, call setAutoCancel()
with true when building the notification: mb.setAutoCancel(true);
The accepted solution is not working in Android 8.1 and onwards.
Follow the same steps as in the accepted answer, but update this line:
//Create the PendingIntent
PendingIntent btPendingIntent = PendingIntent.getBroadcast(context, 0, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
See also PendingIntent.FLAG_UPDATE_CURRENT