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 notifi
Using setContentIntent should solve your problem:
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
For example:
NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("title")
.setAutoCancel(true)
.setContentText("content")
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());
Often you might want to direct the user to the relevant content and so might replace 'new Intent()' with something else.
/**
Post a notification to be shown in the status bar.
Obs.: You must save this values somewhere or even pass it as an extra through Intent to use it later
*/
notificationManager.notify(NOTIFICATION_ID, notification);
/**
Cancel a previously shown notification given the notification id you've saved before
*/
notificationmanager.cancel(NOTIFICATION_ID);
Set the flags in notification.flags instead of notification.defaults.
Example:
notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
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.
If you're using NotificationCompat.Builder
(a part of android.support.v4
) then simply call its object's method setAutoCancel
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
Some guys were reporting that setAutoCancel()
did not work for them, so you may try this way as well
builder.build().flags |= Notification.FLAG_AUTO_CANCEL;
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 :
notification.flags |= Notification.FLAG_AUTO_CANCEL;