I am posting this answer since the one chosen as the best solution does not work for me.
This is an updated version:
First create this class of service:
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);
Then declare your service this way in the manifest label:
<service android:enabled="true" android:name=".ExitService" android:exported="false" android:stopWithTask="false" />
Now just start the service where you want to do something before closing the application.
Intent intent = new Intent(this, ExitService.class); startService(intent);
source share