问题描述
我知道,这里有很多关于保存/检索数据的问题.我自己在 find 查找问题,并且真的认为我可以设法找到我的答案而无需提出问题",但我开始想知道一些我在这里没有看到答案的东西.
I know, there are plenty of questions in regards to saving/retrieving data on here. I was doing find looking things up on my own and really thought I could manage to find my answers without having to "ask a question", but I began to wonder something that I haven't seen an answer for on here.
我的情况:
当然,我正在制作一个应用程序.关闭应用程序后,我想保存一个简单的数字数组(0 或 1)或布尔值.在启动应用程序时,我想搜索该数组(如果存在)并检索它以在应用程序中使用.
Naturally, I'm making an app. Upon closing the app, I want to save a simple array of numbers (0 or 1) or boolean values as it were. Upon starting the app, I want to search for that array, if it exists, and retrieve it for use within the app.
我开始将我的代码放入将使用数组的活动中.但是,我开始怀疑是否必须将覆盖的 onStop()
函数复制/粘贴到我的所有活动中?或者我是否在主要活动中执行此操作并以某种方式链接其他活动.
I began placing my code into the activity in which the array would be used. But, I started wondering if I would have to copy/paste the overridden onStop()
function into all of my activities? Or do I do it in the main activity and somehow link the other activities.
基本上,无论应用程序关闭时应用程序当前处于什么状态/活动,我都希望能够保存 int/bool 数组并在应用程序启动时将其打开.
Basically, no matter what state/activity the app is currently on when the app is closed, I want to be able to save the array of int/bool and open it back up when the app is started.
也许我不知道如何搜索我想要的东西,所以解释它是正确的做法.
Maybe I didn't know how to search for what I wanted, so explaining it felt like the right thing to do.
我不介意进行更多搜索,但如果有人至少能指出我正确的方向,我将非常感激.
I don't mind doing more searching, but if someone would point me in the right direction at the very least, I'd be extremely grateful.
如果有比我所描述的更好的方法来做我想做的事(例如,使用不同的状态而不是 onStop()
),请随意抛出想法.这是我第一次真正不得不处理活动的生命周期,即使在浏览了 android 开发教程之后我也有点困惑.我真的认为他们在大多数情况下做得不好.
If there's a better way to do what I want than what I described (i.e. using a different state instead of onStop()
, for instance), please feel free to throw out ideas. This is my first time actually having to deal with the activities' lifecycles and I'm a bit confused even after looking through the android development tutorials. I really think they're poorly done in most cases.
推荐答案
当您的应用程序需要保存一些持久性数据时,您应该始终在 onPause()
方法中进行,而不是在 onStop()代码>.因为如果 android 操作系统杀死了你的进程,那么永远不会调用
onStop()
和 onDestroy()
方法.同样在 onResume()
方法中检索数据.
When you application needs to save some persistent data you should always do it in onPause()
method and rather than onStop()
. Because if android OS kills your process then onStop()
and onDestroy()
methods are never called. Similarly retrieve data in onResume()
method.
这篇关于在关闭应用程序并检索该数据时保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!