当 Android 应用程序恢复时,全局变量的值是否会被重置?
当应用程序被放入后台并稍后恢复到活动时,另一个活动中设置的静态类变量是否可能已被垃圾收集器重置并将值设置为零?
我在主活动中使用了几个公共静态 int 变量,并将它们用作各种其他活动中的全局变量。我在 Android Market 的开发者控制台中收到了一份崩溃报告,其中我能找到的唯一解释是应用程序恢复到一个 Activity,该 Activity 使用另一个类中的 public static int 变量的值,但该值已(神秘?)变为零。我知道应用程序首次启动时它被设置为其他内容。这有可能吗?
如果我的怀疑是正确的,当应用程序置于后台时,保留全局变量值的推荐方法是什么?将它们保存在 OnPause() 中的 SharedPreferences 中还是使用 onSaveInstanceState 或其他方法?
When an app have been put into the background and later resumes to an activity, is it possible that static class variables set in another Activity could have been reset by the garbage collector and have got the value set to zero?
I use a couple of public static int variables in my main Activity and use them as global variables in various other Activities. I have received a crash report in the developer console from Android Market where the only explanation I can find is that the app resumes to an Activity which uses the value of a public static int variable in another class, but the value has (mysteriously?) become zero. I know that it was set to something else when the app first started. Is this at all possible?
If my suspicion is correct, what is the recommended way to preserve the values of the global variables when an app is put in to background? Save them in SharedPreferences in OnPause() or use onSaveInstanceState or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它不会“被垃圾收集器重置”。但是,该进程可能已被 Android 终止,以释放内存供其他应用程序使用。
静态数据成员应该只是缓存。无论发生什么情况(例如,进程被终止),您想要保留的数据都需要保存在某些持久存储中,例如平面文件、SharedPreferences 或数据库。
onPause()
可能是安排保留该数据的时间,因为此后的任何时间,您的进程都可能会终止,恕不另行通知。It would not be "reset by the garbage collector". However, the process may have been terminated by Android, to free up memory for other applications.
Static data members should only be a cache. Data you want to retain regardless of what happens (e.g., process being terminated) needs to go in some persistent store, such as a flat file,
SharedPreferences
, or database.onPause()
is a likely time to arrange to persist that data, as any time after that, your process could be terminated without notice.小心静态变量。请点击链接获取有关 Singleton 的说明(也使用静态变量来维护状态):https://stackoverflow.com/a/ 9004638/1127492
Be careful with static variables. Follow the link for an explanation concerning Singleton (which also use a static variable to maintain state): https://stackoverflow.com/a/9004638/1127492
您可以在活动中的 onDestroy 方法或具有退出响应的其他方法上将此值保存在 SQLite 上。
You can save this values on SQLite on method onDestroy in activity or another method with response to exit.