views:

311

answers:

2

Hello, I have read many examples of how to create notification messages. What i wanted to achieve, is because the notification will be executed by a widget, i would like the notification intent when clicked to clear it self when the user clicks on it.I do not have an activity to return to. The notification for my purposes will just plainly notify, nothing else. So what would be the code of an intent that just clear/cancel itself. The code below is an activity launched by a button(button code not included) the notification will be fired up by a background service.

CharSequence title = "Hello";
CharSequence message = "Hello, Android!";
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Notification notification = new Notification(R.drawable.icon,"A New Message!",System.currentTimeMillis());

notification.defaults=Notification.FLAG_ONLY_ALERT_ONCE+Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, AndroidNotifications.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);

notification.setLatestEventInfo(AndroidNotifications.this, title,message, pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);

Thanks

A: 

The only way I can see of doing this is to have your Notification's Intent point to a background Service. When this Service is launched, it would clear the given Notification using NotificationManager.cancel(int id). The Service would then stop itself. It's not pretty, and would not be easy to implement, but I can't find any other way of doing it.

iandisme
If you want by code to cancel the notification use the `NOTIFICATION_ID` on cancel call.
Pentium10
Yes i would be calling that from a button, but i would like to call that from the code when the user selects the notification.
John
A: 

Check out FLAG_AUTO_CANCEL

Bit to be bitwise-ored into the flags field that should be set if the notification should be canceled when it is clicked by the user.

Pentium10
My code is already using FLAG_AUTO_CANCEL but actually the notification is not going away on click.
John
Your code uses wrong (puts in defaults field), you need to bitwise-or in the flags field like this: `notification.flags |= Notification.FLAG_AUTO_CANCEL;`
Pentium10
Thanks notification.flags |= Notification.FLAG_AUTO_CANCEL; Worked.
John
Important on SO, you have to mark accepted answers by using the tick on the left of the posted answer, below the voting. This will increase your rate.
Pentium10