Skip to content Skip to sidebar Skip to footer

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() met

Solution 1:

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

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

Solution 2:

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.

Solution 3:

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.

Post a Comment for "How To Stop Android Service When App Is Closed"