onDestroy() Doesn't get called all the time

405 Views Asked by At

I'm creating a temp file in the application. And when the app is destroyed I need to delete that file. Currently I'm calling this deleteTempFile() method in the onDestroy() method. But as I found out in the developers guide its not guaranteed to be called when app is killed. What should be the correct way of achieving this?

Note that onDestroy is not called when we press home button and then long press it again to get the task manager and swipe the app to kill it.

3

There are 3 best solutions below

3
On

Try doing it in onSaveBundleInstances(Bundle outBundle)

1
On
@Override
public void onPause() {
   super.onPause()
   if (isFinishing())
      deleteTempFile();
}
1
On

onDestroy() will not work all time so alternate way is you should use onBackPressed() method for deleteTempFile().