How to handle running service when app is killed by swiping in android?



If my app is running and i press home button, the app goes in background. Now if I long press the home button and kill the app by swiping it from the recent app list, none of the events like onPause(), onStop() or onDestroy() gets called rather the process is terminated. So if i want my services to stop, kill notifications and unregister listeners, how can i do that? I read quite a few articles and blogs but didn’t get any useful information and I haven’t found any documentation about it.
Any help would be appreciated.
Thanks in advance.


I just resolved a similar kind of issue.

Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.

Inside your Manifest file, keep flag stopWithTask as true for Service. Like:

    android:stopWithTask="true" />

But as you say you want to unregister listeners and stop notification etc, I would suggest this approach:

  1. Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

        android:stopWithTask="false" />
  2. Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).

    public void onTaskRemoved(Intent rootIntent) {
        //unregister listeners
        //do any other cleanup if required
        //stop service

Refer my question for more details, which contains other part of code, too.

Hope this helps.

Answered By – MysticMagicϡ

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More