How to stop Android service when app is closed

Kamil picture Kamil · Mar 28, 2015 · Viewed 20.5k times · Source

I'm trying to keep service running continously until user close app.

I'm using startService() method from onCreate() method of my main activity and stopService() in onDestroy() method.

Now I have problem, because it seems that my main activity dies and is re-created when I rotate device or when I turn off screen.

How can I stop my service only when user stops app manually?

Answer

CVA picture CVA · Jul 23, 2015

Set the below attribute in your service tag in the manifest file,

<service android:name="service" android:stopWithTask="true"/>

adding this will call the ondestroy() of the service when the task is removed (app closed from recent apps list).