I have a disk cache which I need to close when the app is closing. Where is the best place to do this?
-Overriding the activities onDestroy method and checking if it’s the task root:
@Override
protected void onDestroy () {
if (this.isTaskRoot()) {
//I only want to close it if this is the last activity of the app
CloseCache();
}
super.onDestroy();
}
According to the documentation, Activity.onDestroy() may not be called when the system just kills the app, so in this case this would leave the cache opened.
-Using a Service running in the same process and closing the cache from its onDestroy callback? Is Service.onDestroy() always called by the system upon destruction of the process?
-Some other way I’m not aware of?
You could consider doing this step in the onStop() method which is “Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.” Then in your onRestart() method you can reclaim the cache if need be.
http://developer.android.com/reference/android/app/Activity.html#onStop%28%29