问题
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 ?
回答1:
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();
}
回答2:
I don't know if it's correct but on my app i'm stopping the foreground service here and it works.Check the code
private void stopForegroundService() {
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
UPDATE
Call the stopservice
from your main class somehow(not from onDestroy) like this:
Intent intent = new Intent(this, MyForeGroundService.class);
intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
startService(intent);
MyForegroundService.java
private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";
public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
}
}
return START_STICKY;
}
private void stopForegroundService() {
Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
来源:https://stackoverflow.com/questions/53334235/how-to-properly-stop-a-foreground-service