我有一些不清楚的情况:
在最后一个引用持有 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.
通过一些帖子:
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/