gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:17:46 24 4
gpt4 key购买 nike

当应用程序被置于后台并稍后恢复到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com