As specified in the Android documentation, it is not guaranteed that onDestroy()
will be called when exiting your application.
"There are situations where the system will simply kill the activity's hosting process without calling this method"
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:
public class ClosingService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// Handle application closing
fireClosingNotification();
// Destroy the service
stopSelf();
}
}
Declare / register your service in the manifest (within the application tag, but outside any activity tags):
<service android:name=".services.ClosingService"
android:stopWithTask="false"/>
Specifying stopWithTask="false"
will cause the onTaskRemoved()
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.
onDestroy()
will not be called. Do not depend upononDestroy()
. If it is called, feel free to use it to clean things up optimistically. But, your app needs to be able to deal withonDestroy()
not being called, on any component (Activity
orService
). – Kane