Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stopForeground(true) called from onDestroy() doesn't remove a notification

Tags:

android

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.

like image 913
AlexKost Avatar asked Apr 28 '17 00:04

AlexKost


2 Answers

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

like image 175
Victor Avatar answered Oct 22 '22 21:10

Victor


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:

  1. Stop the service from within it in onStartCommand() (or elsewhere within the service).
  2. StopForeground(true)
  3. Remove notification channel (this what actually cleaned all the notifications).

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

like image 22
NoamStolero Avatar answered Oct 22 '22 23:10

NoamStolero