Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel notification after application is closed from background

I have an activity that shows a notification on notification bar. If the user goes to the background pressing the home button I keep the notification (that's what I need), but when the user closes the application I need to cancel the notification and that's my problem.

  • I tried to cancel notification on onDestroy but it´s not fired.
  • I tried to set setOngoing true for the notification.

How could I deal with this? Every time the user goes background and then close the app I need to remove the notification from the notification bar, but if the user keep the application in background I need the notification.

like image 977
user2494863 Avatar asked Aug 30 '13 16:08

user2494863


People also ask

How to remove foreground service notification in Android?

User can dismiss notification by default Starting in Android 13 (API level 33), users can dismiss the notification associated with a foreground service by default. To do so, users perform a swipe gesture on the notification.

What is a foreground notification?

According to the official android documentation, a foreground service performs operations that are noticeable to the user. It shows a status bar notification, so that users are actively aware that your app is performing a task in the foreground and is consuming system resources.

How to stop foreground service?

You can tap on the Stop button to stop the foreground service.


2 Answers

You have your notification an ID when your created it, right?

Then all you have to do is use that ID to cancel it.
For example:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(4);

on destroy is fired when they back out of your app or if you call finish() on your activity.

like image 138
tyczj Avatar answered Nov 15 '22 04:11

tyczj


I created an async task that runs forever and now when I remove the application from recent list, the onDestroy is called.

like image 45
Sefa Aras Avatar answered Nov 15 '22 05:11

Sefa Aras