简体   繁体   中英

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!

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM