java - 如何在 Android 中即将被垃圾收集时将静态成员保留在共享首选项中

标签 java android garbage-collection android-sharedpreferences

我在 Utility 类中有一个静态成员,我的大部分 Activity 都会访问它来存储历史信息。当 Utility 类即将被 GC 时,我想保留这个静态成员。我尝试了以下选项。

  1. finalize() method implementation:

我已经覆盖了 Utility 类的 finalize()(我知道并不总是保证 finalize() 会运行)以在 Shared Preferences 中保留静态成员。但是 finalize() 根本没有被调用!

  1. Implementing onDestroy() in each activity to persist static member

我开始在所有访问这个静态成员的 Activity 中实现onDestroy(),当每个 Activity 即将被销毁时,静态成员将被持久化在SharedPreference。这是有效的,但写入共享首选项的情况非常频繁,导致不必要的重复持久化,我想避免这种情况。

有没有更好的方法来做到这一点?

最佳答案

不要开始实现不良习惯做法。考虑到 documentation of onPause() ,这是您应该保留数据的地方。

This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.

In situations where the system needs more memory it may kill paused processes to reclaim resources. Because of this, you should be sure that all of your state is saved by the time you return from this function. In general onSaveInstanceState(Bundle) is used to save per-instance state in the activity and this method is used to store global persistent data (in content providers, files, etc.)

您无法保证,对于任何方法,您都会达到存储数据的程度。

考虑到您的 Utility 类只有静态方法和成员,并且您永远不会创建它的实例,所以永远不会调用 finalize()。如果您使用的是 Utility 类的实例,只需将存储持久保存在您希望它最后可访问的位置。

考虑使用 onDestroy() 也不是一个好主意。 The documentation明确说明这一点。

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

关于java - 如何在 Android 中即将被垃圾收集时将静态成员保留在共享首选项中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37020882/

相关文章:

java - 文件是否附加在文件字段中?

java - GWT注入(inject): need good practice

java - 使用集合对列表进行排序会导致错误

java - 如何更改微调器的文本颜色

java - Kotlin-Java 互操作不适用于可变参数

android - 在 Espresso 中,指定要使用当前可见的 AdapterView

java - 在通用父类(super class)中 Autowiring 通用组件

System.gc()后Java弱引用没有被释放

logging - 如何为 Apache Kafka 代理启用 GC 日志记录,同时防止日志文件覆盖并限制磁盘空间使用

actionscript-3 - Actionscript 内存管理?