Onclick listener for Notification buttons in android

余生颓废 提交于 2019-12-22 13:49:33

问题


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?

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:


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



来源:https://stackoverflow.com/questions/24178184/onclick-listener-for-notification-buttons-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!