Stop Android service when app is closed with the t

2019-02-13 06:46发布

问题:

I am working on an app with a foreground service that plays audio for an extended period of time.

I do not want the Android OS to kill my service while it's running in the background, however I want to stop the service if the app is manually closed from the task manager.

The current behavior of my app is that the services continues to run when the app is closed in the task manager.

I've noticed that Spotify achieves the desired effect, how is it accomplished?

回答1:

I think that you can call stopSelf() from onTaskRemoved(). There's also a severely underdocumented android:stopWithTask you apparently can have on the <service> element to automatically stop the service when the task is stopped from the recent-tasks list.

Note that I haven't tried either of these, so YMMV.