Khaled
Khaled

Reputation: 8583

Make Notification cleared by user or once clicked

I have a service that may show a notification, the problem is once the notification is set, it doesn't clear neither when clicked, nor when swiped on. I am using the flag Notification.FLAG_AUTO_CANCEL but it doesn't seem to do anything..

private NotificationManager nm;
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
private final int NOTIFY_ID = 1;
private void showNotification(String date, String name) {
        try{
            CharSequence text = "You have new Event";
            Notification notification = new Notification(R.drawable.small_icon, text, System.currentTimeMillis());
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, viewEvents.class).putExtra("date", date), 0);
            notification.setLatestEventInfo(this, name, "Date: "+date, contentIntent);
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notification.defaults |= Notification.DEFAULT_LIGHTS;
            notification.defaults |= Notification.FLAG_AUTO_CANCEL;
            nm.notify(NOTIFY_ID, notification);
        }catch(Exception e){
            Log.i("Notification",e.toString());
        }
    }

So what am I doing wrong?

Upvotes: 2

Views: 230

Answers (3)

Miguel Maciel
Miguel Maciel

Reputation: 176

I use this code to show/hide notifications:

private Handler handler = new Handler();
private Runnable task = new Runnable() {
@Override
public void run() {
    NotificationManager manager = (NotificationManager) contesto.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent launchIntent = new Intent(contesto.getApplicationContext(), SearchHistory.class);
    PendingIntent contentIntent = PendingIntent.getActivity(contesto.getApplicationContext(), 0, launchIntent, 0);
    //Create notification with the time it was fired
    NotificationCompat.Builder builder = new NotificationCompat.Builder(contesto);
    builder.setSmallIcon(R.drawable.ic_launcher).setTicker("MESSAGE HERE!").setWhen(System.currentTimeMillis()).setAutoCancel(true).setDefaults(Notification.DEFAULT_SOUND).setContentTitle("TITLE").setContentText("MESSAGE").setContentIntent(contentIntent);
    Notification note = builder.build();
    manager.notify(100, note);
}
};

And to invoke just put:

handler.post(task);

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007584

Try using Notification.Builder or NotificationCompat.Builder instead of rolling the Notification manually.

Among other things, this would prevent the bug in your code, where you are applying FLAG_AUTO_CANCEL to defaults rather than flags.

Upvotes: 3

user123
user123

Reputation: 1092

Notification.FLAG_AUTO_CANCEL is commented out in your code.

But in case it isn't then flag Notification.DEFAULT_LIGHTS should be setted in notification.defaults not in notification.flags

Upvotes: 0

Related Questions