How to stop Android service when app is closed

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


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.