I understand when an activity closes, onDestroy() is called. But this is not done always right? Sometimes, onPause() is called.
So suppose I want to clear some memory when an activity closes, where exactly do I do it? Since onDestory may not be called, I cannot keep it there either right?
Elaborating:
I have 2 activities A1 and A2. A1 is hsown in the startup of the app. A1 calls A2 later. Suppose I create a class object in onCreate() of Activity A1. This object must be deleted when the I exit the app, i.e when the app is no longer visible. Is the best place to do this onDestroy() or onStop() of A1?
I guess onPause() may not be the right place, because onPause() will be called when A1 calls A2 and I dont want to delete the object then.
-Kiki
I think you mean onPause(), there is no onSuspend() method. If your activity closes cleanly, it will call onStop() and onDestroy().
If the system is running low on memory and wants to kill your activity, then onPause() is guaranteed to be called before your process is killed, but that’s the only guarantee. The methods onStop() and onDestroy() may not be called. So you should cleanup in onPause().
However… don’t forget that your activity can transition many times between onResume() and onPause(), so you don’t want to do too much allocations and cleanups in those two methods, they should be quick.
You have to decide how best to cleanup in onPause(), and what you actually have to do, if your activity needs to do something before it is killed off during low memory situations.