I want to remove a notification after my foreground service is being destroyed. I tried to call stopForeground(true)
from onDestroy()
and from unbind()
. Although onUnbind() and onDestroy() were called(I can see it from logs) notification is still there. I stop the service by calling unbindService(playerConnection)
and stopService(this)
from my activity.
Why it's not working this way? Any ideas on how to remove a notification when service is destroyed?
UPATE: one interesting thing I've noticed when playing around with the notification. I've made a special method inside the service:
fun hideNotification() {
stopForeground(true)
Log.d("PlayerService", "hideNotification")
}
Than I call it from my activity when the button is pressed. And it removes the notification. But the same function being called from activity's onStop() or service's onUnbind() or onDestroy() doesn't. I can't understand what the difference between these situations.
After hours of debugging between 2 services, one that removed the notification and the other that doesn't, I found that the only difference between them is that one of them has the android attribute exported to false.
<service
...
...
android:exported="false">
I ignore the reason why setting exported to false make me able to remove the notificatión but I wanted to share this solution
I had the same issue when trying to stop a foreground service and remove all it's notification.
As a workaround i delete the notification channel and recreate it if needed.
What solved it to me was to do as follows:
Example:
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
var stopService : Boolean # Service stop condition
var isRunning : Boolean # stopSelf() raise exception if service is not running.
if (stopService}){
stopForeground(true)
notificationManager.deleteNotificationChannel("channel_id");
if (isRunning){
Log.d(TAG, "Service is running, stopping.")
stopSelf()
}else
Log.d(TAG, "Service is not running, no need to stop.")
return START_NOT_STICKY
}
Some references:
How to remove old notification channels?
What is the proper way to stop a service running as foreground
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