使用Android中的静态变量变量、静态、Android

2023-09-12 00:12:16 作者:清酒无隐

在Android上,使用静态变量的建议的做法? 例如,用Java实现的一个Singleton模式,我通常做的:

In android, are using static variables a recommended practice? E.g, implementing a Singleton pattern in Java, I usually do:

private static A the_instance;
public static A getInstance() {
    if (the_instance == null) {
       the_instance = new A();
    }
    return the_instance;
}

此外,什么时候该得到清理了Android的JVM?

Also, when does this get cleaned up by the Android JVM?

感谢你。

推荐答案

静态字段连接到实例作为一个整体,其又连接到类加载其中装载类。当整个的ClassLoader 被回收 the_instance 将被卸载。我90%肯定发生这种情况时,机器人会破坏应用程序(而不是当它进入的背景下,或暂停,但完全关闭。)

static fields are attached to the Class instance as a whole, which is in turn attached to the ClassLoader which loaded the class. the_instance would be unloaded when the entire ClassLoader is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)

所以,把它当做只要居住为你的应用程序运行。辛格尔顿是一个好主意?人们有不同的看法。我认为这是适当的罚款,用我自己的时候。我不认为答案在Android上改变了。内存使用不是问题本身;如果你需要加载了一堆东西在内存中,这是任何一个问题或不是,不论你是否封装数据的辛格尔顿。

So, think of it as living as long as your app runs. Is Singleton a good idea? People have different views. I think it's fine when used appropriately, myself. I don't think the answer changes much on Android. Memory usage isn't the issue per se; if you need to load a bunch of stuff in memory, that's either a problem or it isn't, regardless of whether you encapsulate the data in a Singleton.