Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Android service when app is closed with the task manager

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?

like image 296
Jacob Tabak Avatar asked Aug 08 '14 15:08

Jacob Tabak


People also ask

How stop service when app is killed Android?

First, the easiest way to do what you're trying to do is to launch an Android Broadcast when the app is killed manually, and define a custom BroadcastReceiver to trigger a service restart after that. Dear Dr Sabri Allani, If your Service is started by your app then actually your service is running on main process.

How do you stop a service app on Android?

In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.

How do I stop programmatically running in the background Android?

To start the service, call startService(intent) and to stop the service, call stopService(intent) .

How do you stop foreground service?

To remove the service from the foreground, call stopForeground() . This method takes a boolean, which indicates whether to remove the status bar notification as well. Note that the service continues to run. If you stop the service while it's running in the foreground, its notification is removed.


1 Answers

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.

like image 198
CommonsWare Avatar answered Oct 15 '22 11:10

CommonsWare