I use startForeground to make my service "persist" in background and not be killed by the OS.
I remove the service in the main activity onDestroy method by calling stopForeground and stopService.
The problem is, when I swipe my app off the recent apps to kill it, the debug session is still running, whereas in the "normal" functioning (without using startForeground), the debug session terminates correctly.
Using adb shell confirms that the app is still running.
startForeground somehow creates a "special" running thread that could not be stopped by simply stopping the foreground and the service.
Any ideas please ?
You can tap on the Stop button to stop the foreground service.
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
if you want to stop your service when you are clearing your application from the recent task, you have to define an attribute stopWithTask
for service in the manifest file like this as shown below
<service
android:enabled="true"
android:name=".ExampleService"
android:exported="false"
android:stopWithTask="true" />
then you can override onTaskRemoved method in the service , this will be called when the application's task is cleared
@Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
//do something you want
//stop service
this.stopSelf();
}
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