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
If you're using
NotificationCompat.Builder
(a part ofandroid.support.v4
) then simply call its object's methodsetAutoCancel
Some guys were reporting that
setAutoCancel()
did not work for them, so you may try this way as wellThe only way I can see of doing this is to have your
Notification
'sIntent
point to a backgroundService
. When this Service is launched, it would clear the givenNotification
usingNotificationManager.cancel(int id)
. TheService
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.Using setContentIntent should solve your problem:
For example:
Often you might want to direct the user to the relevant content and so might replace 'new Intent()' with something else.
Set the flags in notification.flags instead of notification.defaults.
Example:
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.
EDIT :