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

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:

<service
    android:name="com.myapp.MyService"
    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:

    <service
        android:name="com.myapp.MyService"
        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
        stopSelf();  
    }
    

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

Hope this helps.

Leave a Comment