android - Android中的静态单例生命周期

标签 android singleton

我有一些不清楚的情况:

在最后一个引用持有 Activity 被销毁后,静态单例是否会被垃圾回收?因为 Application 中不再有对单例实例的引用。那么我可以依赖单例吗?

官方Android doc :

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way.

通过一些帖子:

https://web.archive.org/web/20160729201921/http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

While developing an application, I found that sometimes some static variables bound to activities happened to be uninitialized even though they’ve previously been initialized! I thought that when a static variable is initialized it stays so for the entire life of the application, but this doesn’t seem to be the case.

换句话说,如果没有任何东西持有对我的静态单例类的引用,那么如何防止它被垃圾收集和销毁?

最佳答案

不,因为如果是单例,它会在其类中存储为 static 字段,通常单例不会被客户端销毁,即您不会放置静态方法 deleteInstance () 设置对 null 的引用,这样如果没有其他人使用它,它就有资格进行垃圾收集。对于静态字段,当加载该类的类加载器被丢弃时,就会发生垃圾回收。

由于这个原因,关键字static本身如果引用Activity对象,可能会造成内存泄漏,所以在使用的时候要非常小心。

关于android - Android中的静态单例生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13891186/

相关文章:

Android:读取正在运行的应用程序的开始时间。只能用于服务吗?

ios - 如何实现在 Swift 中获取初始化数据的 Singleton?

c++ - C++ 编译器会自动将我的函数设置为静态函数吗?

java - 如何读取 DataInputStream 两次或两次以上?

ruby-on-rails - 单例方法与类方法

需要 Java Singleton 解释

java - 全局对象的成员变量也应该设为全局吗?

android - 在多个 Android 应用程序之间共享和持久化数据

java - 如何在 Android 的锁定屏幕上显示文本

android - 无法将 Android 连接到 Web 服务