将数据保存到活动的onDestroy方法中 [英] Save data in activity's onDestroy method

查看:231
本文介绍了将数据保存到活动的onDestroy方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个任务列表,并具有Project对象,该对象包含所有任务(和元数据).我使用动作日志,因此当任务更改时,我不会立即将其保存到数据库中,而只是将其保留在内存中以在活动完成时转储到数据库中. Activity的onDestroy方法是最好的选择:如果没有调用onRetainNonConfigurationInstance方法,我将启动服务以保存项目(一个人的实例存储在Application中).保存是昂贵的:在DB项目中有修订版本,因此我保存新数据,更改当前修订版本并删除先前修订版本的数据.因此,我不担心应用程序突然停止.

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.

但是,到文档中必须do not count on this method being called as a place for saving data.

还有其他保存数据的地方吗?

Is there any alternative place for saving my data?

推荐答案

并非总是会调用OnDestroy.来自生命周期文档-

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

当您的活动收到对onStop()方法的调用时,它不是 不再可见,应该释放几乎所有不可见的资源 用户不使用它时需要它.活动停止后, 如果需要恢复系统,系统可能会销毁实例 记忆.在极端情况下,系统可能会扼杀您的应用程序 无需调用活动的最终onDestroy()回调即可进行处理,因此 使用onStop()释放可能泄漏的资源很重要 记忆.

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.

尽管在onStop()之前调用了onPause()方法,但您应该 使用onStop()执行更大,更占用CPU的关闭 操作,例如将信息写入数据库

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

请参见停止活动

这篇关于将数据保存到活动的onDestroy方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆