TheModularMind TheModularMind - 1 month ago 9
Android Question

Notification setAutoCancel(true) doesn't work

I'm trying to show a notification that has to be deleted when user tap on it.
I'm using

NotificationCompat
class to build my notification and I call
setAutoCancel(true)
on my
builder
. This is the piece of code:

NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setAutoCancel(true)
.setContentText("content");
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());


The notification is correctly added but when I tap on it nothing happens! Where I'm wrong?

Answer

Using setContentIntent should solve your problem:

.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));

In your 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.

I uploaded a demo to github.

Comments