Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly stop a foreground service?

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 ?

like image 852
MMasmoudi Avatar asked Nov 16 '18 08:11

MMasmoudi


People also ask

How do you stop a foreground service?

You can tap on the Stop button to stop the foreground service.

What does it mean when an app is using 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.


1 Answers

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();
    }
like image 81
Hasif Seyd Avatar answered Nov 16 '22 04:11

Hasif Seyd