user1122549
user1122549

Reputation: 748

Android Notification not getting dismissed on click/swipe

I am creating notification from a intent service using startForeground(id,notification).

Random r=new Random();
int id=r.nextInt(9999);

Builder notice2=new Notification.Builder(getApplicationContext())
    .setContentTitle(call.getName())
    .setAutoCancel(true)
    .setContentIntent(intent)
    .setContentText("content")
    .setSmallIcon(com.project.calltracker.R.drawable.ic_alert)
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), com.project.calltracker.R.drawable.ic_logo));

startForeground(id, notice2.getNotification());

Here I have set AutoCancel(true)

But when I click on the notification it does not disappear??

I am really confused. I have tried everything for last couple hours but still no luck!

Please help!

Thanks!

Upvotes: 5

Views: 7973

Answers (3)

Radek
Radek

Reputation: 166

AutoCancel does not work when service is still on foreground. To allow dismiss by swipe, the stopForeground() must be called:

startForeground(id, notice2.getNotification());
stopForeground(false); //false - do not remove generated notification

Upvotes: 2

user1122549
user1122549

Reputation: 748

I found the answer from a answer to my other post. Basically there can be only one foreground service. Using startForeground() to generate the notification means that as long as this service is running the notification cannot be removed.

Instead using NotificationManager.notify() simply generates the notification. Setting AutoCancel(true) for this notification makes it disappear on swipe/click.

Thanks!

Upvotes: 12

Salman Khakwani
Salman Khakwani

Reputation: 6714

You can modify your code like this, so that the Notification will be canceled when clicked :

Random r=new Random();
int id=r.nextInt(9999);

Builder notice2=new Notification.Builder(getApplicationContext())
    .setContentTitle(call.getName())
    .setAutoCancel(true)
    .setContentIntent((PendingIntent.getActivity(getApplicationContext(), id, intent, PendingIntent.FLAG_CANCEL_CURRENT))
    .setContentText("content")
    .setSmallIcon(com.project.calltracker.R.drawable.ic_alert)
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), com.project.calltracker.R.drawable.ic_logo));

startForeground(id, notice2.getNotification());

Instead of using simple plain Intent, i have used PendingIntent with appropriate Flag setup for canceling the current Notification.
Here are some informative links regarding PendingIntent :

  1. http://developer.android.com/reference/android/app/PendingIntent.html
  2. What is an Android PendingIntent?

I hope this helps.

Upvotes: 4

Related Questions