Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

android - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...