Save data in activity's onDestroy method

此生再无相见时 提交于 2020-01-11 01:48:08

问题


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?


回答1:


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




回答2:


You should not use onDestroy() method for saving data. Instead, you should use internal/external storage space or write your code in the onPause() method.




回答3:


You should be using onStop

Activity docs

You could also use onPause, but that will be called whenever you navigate away from the Activity, including turning off the screen.




回答4:


According to the Activity Lifecycle documentation you should save your data in onPause() or onSaveInstanceState(Bundle).

The methods onDestroy() and onStop() might never be called before the activity is shut down.

Excerpts from the Activity Lifecycle documentation:

protected void onDestroy ()

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in eitheronPause()or onSaveInstanceState(Bundle), not here.

protected void onStop ()

Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.



来源:https://stackoverflow.com/questions/13956528/save-data-in-activitys-ondestroy-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!