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.
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.
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.
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.
You can tap on the Stop button to stop the foreground service.
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.
I created an async task that runs forever and now when I remove the application from recent list, the onDestroy is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With