即使应用程序关闭后,静态变量还会存在吗?
考虑我的应用程序有一个活动,并且该活动中有一个静态变量。第一次我初始化变量,启动服务并退出应用程序。在某些情况下,我尝试访问我之前初始化的静态变量。有时价值是存在的。但有时会检索到空值。请告知出了什么问题,
提前致谢。
Consider my application has one activity and I have a static variable in that activity. At first time i initialize the variable , starting a service and exit from the application. At some instance am trying to access the static variable which i initialized before. Sometimes the value is present. but at some times null value is retrieved. plz advise whats going wrong
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一旦该活动被 SO 终止,所有内存资源都会返回到系统,因此您会丢失该变量中的数据。如果活动进入后台,该值将被保留
Once the activity is killed by the SO, all the memory resources are back to the system, so you lose the data in that variable. If the activity goes into background instead, the value will be retained
您不能依赖静态变量无限期地保留。当您的应用程序终止时,您的静态数据就会消失。如果需要永久存储某个值,请将其保存到数据库、文件系统或其他存储方式。
You cannot rely on a static variable to persist indefinitely. When your application terminates, your statics are gone. If you need to store a value permanently, persist it to a database, filesystem or some other means of storage.
如果您想在退出应用程序后存储值,也许您应该考虑使用 共享首选项。
If you want to store values even after you exit your app, maybe you should consider using Shared Preferences.