当app退出时如何破坏静态字段?

时间:2013-04-14 03:22:14

标签: android static garbage-collection singleton destroy

我的应用程序中有一个singleton类,其定义有点像:

public class SingletonTest {
    private SingletonTest() {}

    private static SingletonTest instance = new SingletonTest();

    public static SingletonTest getInstance() {
        return instance;
    }
}

当我退出我的应用程序并再次打开时,instance尚未再次初始化,因为前者未被销毁且仍在JVM中。但我想要的是每次进入我的应用程序时初始化静态字段。那么,我应该在onDestroy()方法中做些什么呢?非常感谢!

2 个答案:

答案 0 :(得分:3)

只要应用程序保留在内存中,您的静态变量就会保留在内存中。 这意味着,静态变量将与您的应用程序一起自动销毁。

如果你想要一个单例的新实例,你需要创建一个静态方法来重新初始化你的单例,并在你的应用程序对象的onStart或你启动的第一个活动(或者你需要的时候)中调用它。 p>

private Singleton() {}
private static Singleton mInstance;

//use this method when you want the reference
public static Singleton getInstance() {
    //initializing your singleton if it is null
    //is a good thing to do in getInstance because
    //now you can see if your singleton is actually being reinitialized.
    //e.g. after the application startup. Makes debugging it a bit easier. 
    if(mInstance == null) mInstance = new Singleton();

    return mInstance;
}

//and this one if you want a new instance
public static Singleton init() {
    mInstance = new Singleton();
    return mInstance;
}

应该这样做。

答案 1 :(得分:1)

根据您的说法,似乎Singleton不适合您想要做的事情。您应该声明一个将由方法onCreate()/onStart()onStop()/onDestroy()初始化/清除的实例变量。

请参阅this graph了解活动生命周期。

来源:http://developer.android.com/reference/android/app/Activity.html