Onclick listener for Notification buttons in andro

2019-05-21 10:21发布

I have created a notification with a button for API versions more than 16.

Notification and button are coming up properly. I would like to dismiss the notification on clicking the button or notification.

On clicking the notification the notificiation gets cleared but it is not the same when I click on the button it doesn't do anything.

I am not sure how to listen to button click on Notification? Can somebody help me fix this?

enter image description here

Look at the screen shot... So when I click on AndroidProject - The notification is cleared and an intent is called accordingly, but when I click on Close or the red X mark notification is still there but intent is called. How do I implement to clear notification when I click on the close or X button?

Here is what I have tried:

Intent notificationIntent = new Intent(context, ServicetocancelAlarm.class);
PendingIntent contentIntent = PendingIntent.getService(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Resources res = context.getResources();

Notification noti = new Notification.Builder(context)
    .setContentTitle(res.getString(R.string.app_name))
    .setContentText(res.getString(R.string.cancelText))
    .setSmallIcon(R.drawable.ic_launcher)
    .setTicker(res.getString(R.string.ticker))
    .setAutoCancel(true)
    .setWhen(System.currentTimeMillis())
    .setContentIntent(contentIntent)
    .addAction(R.drawable.cancel, "DISMISS", contentIntent).build();

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);

Thanks!

1条回答
ら.Afraid
2楼-- · 2019-05-21 10:54

When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:

notify(int id, Notification notification)

for cancel

cancel(int id)

read below link:-

http://developer.android.com/reference/android/app/Notification.html

Dismiss Ongoing Android Notification Via Action Button Without Opening App

查看更多
登录 后发表回答