I have a simple foreground service that runs a timer and shows an ongoing notification with a progress bar. However, the following code on the service does not cause the notification to be removed when the app runs on my Galaxy S21 Ultra. It works perfectly fine on the emulator running the same version of Android (version 11) and my S6 running Android 7.
StopForeground(StopForegroundFlags.Remove);
I've tried so many ways to get this working I couldn't possibly list them all here. I don't want to stop the service (which doesn't remove the notification anyway despite people saying it does; I tried it).
It's almost like it thinks I'm calling
StopForeground(StopForegroundFlags.Detach);
even though I'm not - and I why would it work that way on this specific device (and run correctly in an emulator running the same version of Android)?
I'm flummoxed.
Edit: I should mention that in all cases, the notification disappears after the app is closed. I call StopForeground(StopForegroundFlags.Remove) in the OnTaskRemoved event in the service class before stopping the service. When I comment StopForegound out, the notification still disappears when the app is closed on the S21. Which means that a) my call to StopForeground is redundant and b) stopping the service in this way does behave as expected.
I need to experiment more. There's another way I can stop the service when I want to remove the notification, which is to tell the service to stop itself (instead of relying on OnTaskRemoved to do it).
I really don't want to have to start and stop the service every time the timer needs to run though, especially as the user can do this repeatedly at will. And it still wouldn't explain why it's only a problem on the S21 and not on the S6 or the emulator, making it a shoddy workaround.
Edit 2: I've now tried stopping the service when the user taps stop (by calling StopSelf on the service), instead of calling StopForeground. The same problem seems to happen. The notification persists on the S21, but it's even worse as restarting the service when play is tapped doesn't replace the notification. But again, it works as expected on the emulator (I haven't tried the S6 this time). This is bizarre.