We see the apps which we didn't close, like this
But when we want to close an app from this screen (below image), the method onDestroy() isn't called, however the app is closed. I need to call onDestroy() when the app is closed in this way. How can I do this?
As specified in the Android documentation, it is not guaranteed that
onDestroy()
will be called when exiting your application.https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29
Instead, you can create a service which will be notified when the Task your activities are running inside is destroyed.
Create the service class:
Declare / register your service in the manifest (within the application tag, but outside any activity tags):
Specifying
stopWithTask="false"
will cause theonTaskRemoved()
method to be triggered in your service when the task is removed from the Process.Here you can run your closing application logic, before calling
stopSelf()
to destroy the Service.