Kamil
Kamil

Reputation: 13931

How to stop Android service when app is closed

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?

Upvotes: 35

Views: 29836

Answers (3)

CVA
CVA

Reputation: 1567

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

Upvotes: 117

CommonsWare
CommonsWare

Reputation: 1006674

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.

Upvotes: 17

tausif
tausif

Reputation: 54

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.

Upvotes: -21

Related Questions