I'm working on a music app, and I want stop the service when user removes the application from the recent list and not when the first activity is destroyed(because when user clicks back back until app minimizes, in that case first activity is also getting destroyed). Please help.
How to detect app removed from the recent list?
26.4k Views Asked by Naresh Gunda AtThere are 3 best solutions below

Im posting this answer, since the chosen as best solution was not working for me.
This is the updated version:
First create this service class:
public class ExitService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
//do something you want before app closes.
//stop service
this.stopSelf();
}
}
Then, declare this way your service in the manifest label:
<service
android:enabled="true"
android:name=".ExitService"
android:exported="false"
android:stopWithTask="false" />
Now, just start the service wherever you want to do something before your app closing.
Intent intent = new Intent(this, ExitService.class);
startService(intent);

The last answer didn't work for me (I am using API 29). I looked up in the Javadoc of the onTaskRemoved function and saw the following instruction: "If you have set {android:stopWithTask}, then you will not receive this callback; instead, the service will simply be stopped."
So, all I got to do is to remove this line (android:stopWithTask="false") from the manifest and it worked just fine.
This is the updated code in the manifest file:
<service
android:enabled="true"
android:name=".ExitService"
android:exported="false"/>
Yes, you can either do that using
stopWithTask
flag astrue
for Service in Manifest file.Example:
OR
If you need event of application being removed from recent list, and do something before stopping service, you can use this:
So your service's method
onTaskRemoved
will be called. (Remember, it won't be called if you setstopWithTask
totrue
).Hope this helps.