Save data in activity's onDestroy method

ryabenko-pro picture ryabenko-pro · Dec 19, 2012 · Viewed 13k times · Source

I'm writing a tasklist and have Project object, which holds all the tasks (and metadata). I use action log, so when tasks changes i do not save it immediately to database, just keep it in memory to dump in database on activity finish. Activity's onDestroy method is best place for this: if no onRetainNonConfigurationInstance method was called I start service to save project (one's instance is stored in Application). Saving is expensive: In DB project have revision, so I save new data, change current revision and delete previous revision's data. So i do not afraid of suddent application stop.

BUT, aсcording to documentation i must do not count on this method being called as a place for saving data.

Is there any alternative place for saving my data?

Answer

iagreen picture iagreen · Dec 19, 2012

OnDestroy is not always going to be called. From the lifecycle docs --

When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.

Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database

see Stop Your Activity