30

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Kamil
  • 13,363
  • 24
  • 88
  • 183

3 Answers3

111

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).

CVA
  • 1,477
  • 1
  • 14
  • 23
  • 3
    In my case, it didn't work because I was starting the service using AlarmManager. But its seems to be the correct answer for the case of services opened inside activity for instance. – Bruno Morais Jun 15 '16 at 23:59
  • 1
    I want my service to stop when the app is cleared from the recent tasks. And stopWithTask="true" works in this case. But I don't want my service to shutdown when we exit the app with the back press. How can I do that? – Wijay Sharma Sep 18 '19 at 12:47
  • @WijaySharma Check out Android foreground service – CVA Sep 18 '19 at 12:52
  • 1
    I had neglected to stop my service when the app exited. So next time it ran, there were two copies of the service running . Nasty bugs ensue! – quilkin Jan 13 '21 at 21:35
  • This works but `onDestroy()` is **not** called when using this flag! An alternative would be to override `onTaskRemoved(Intent?)` in which you can then call `stopSelf()`. That way `onDestroy()` is called if you desire so. – Lorion Jun 16 '21 at 04:11
  • how can I kill the service even user goes to the background? – Madhav Jan 10 '23 at 05:25
17

I mean intentional app close. After user swipe out app on "recent apps" screen.

That is not "closing the app", in terms of Android. That is "removing the task" (or sometimes "stopping the task" -- Google is not very consistent on the terminology).

Your service should be called with onTaskRemoved() when the task is removed. However, that should be both when the user manually removes the task via the overview screen (a.k.a., recent-tasks list) and when the task naturally goes away on Android 4.4 and below because the task is too old.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
-20

Start by adding the android:configChanges node to your Activity's manifest node for stoping restart activity when device rotate.

android:configChanges="keyboardHidden|orientation"

Now for detecting a closing application event, think the ways user can close app manually. In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.

tausif
  • 56
  • 1
  • 9