Judking
Judking

Reputation: 6371

How to destroy static field when app exits?

I got a singleton class in my application, which is defined just somewhat like:

public class SingletonTest {
    private SingletonTest() {}

    private static SingletonTest instance = new SingletonTest();

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

When I exit my application and open again, the instance has not been initialized again because the former one is not destroyed and still in JVM. But what I want is to initialize the static field every time I enter my application. So, what should I do in the onDestroy() method? Thanks a lot!

Upvotes: 2

Views: 2511

Answers (2)

Pierre Laporte
Pierre Laporte

Reputation: 1215

From what you are saying, it seems that Singleton is not suited for what you want to do. You should declare an instance variable that would be initialized/cleared by the methods onCreate()/onStart() and onStop()/onDestroy().

See this graph for the Activity lifecycle.

Source : http://developer.android.com/reference/android/app/Activity.html

Upvotes: 1

Joey Roosing
Joey Roosing

Reputation: 2155

Your static variable will remain in memory as long as your application stays in memory. This means that, a static variable will be automatically destroyed together with your app.

If you want a new instance of your singleton, you will need to create a static method that reinitializes your singleton and call it in the onStart of your application object or the first activity you launch(or whenever you need it)

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;
}

something like that should do.

Upvotes: 3

Related Questions