android - 当 Android 应用程序恢复时,全局变量的值是否会被重置?

标签 android background global-variables resume

当应用程序被置于后台并稍后恢复到 Activity 时,另一个 Activity 中设置的静态类变量是否可能已被垃圾收集器重置并将值设置为零?

我在我的主 Activity 中使用了几个公共(public)静态 int 变量,并将它们用作各种其他 Activity 中的全局变量。我在 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?

它不会被“垃圾收集器重置”。但是,该进程可能已被 Android 终止,以释放内存供其他应用程序使用。

what is the recommended way to preserve the values of the global variables when an app is put in to background?

静态数据成员只能是缓存。无论发生什么情况(例如,进程被终止),您想要保留的数据都需要保存在某些持久存储中,例如平面文件、SharedPreferences 或数据库。 onPause() 可能是安排保留该数据的时间,因为此后的任何时间,您的进程都可能会终止,恕不另行通知。

关于android - 当 Android 应用程序恢复时,全局变量的值是否会被重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9046737/

相关文章:

ruby-on-rails - Rails 3:缓存到全局变量

c - 如何记录函数的全局依赖性?

ios - 如何将 Objective-C 外部常量迁移到 Swift

android - 使用 Firebase TestLab 测试 React Native 应用程序

Android:简单的如何在给定时间后停止媒体播放器

php - 来自带有 jquery 的目录的随机图像选择器

android - 设置 Activity 背景不拉伸(stretch)

xml - 是否有任何 Android XML 文档?

Android布局如何设置特定的固定布局高度

java - 滚动 ListView 时丢失项目背景颜色