HalukO
HalukO

Reputation: 333

Android: Maintaining Global Application State

Android documentation for Application states: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality [i.e. maintain global application state] in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

My request is: Can you explain, and provide code sample that implements the above suggestion for maintaining global state.

Note that there is already a suggestion that recommends subclassing Application: How to declare global variables in Android?

Thank you.

Upvotes: 4

Views: 9039

Answers (2)

Ryan Thomas
Ryan Thomas

Reputation: 479

Correction to StinePike's answer regarding context in the ApplicationState. In the code posted the context passed in to the application state is held on to. If the context passed in is an activity or similar unit then the activity would be leaked and prevented from being garbage collected.

The android documentation for the Application class states you should "internally use Context.getApplicationContext() when first constructing the singleton."

public class ApplicationState {
    private Context applicationContext;
    private static ApplicationState instance;

    private ApplicationState(Context context) {
        this.applicationContext = context.getApplicationContext();
    }

    public static ApplicationState getInstance(Context context) {
        if(instance == null) {
            instance = new ApplicationState(context);
        }
        return instance;
    }
}

Upvotes: 7

stinepike
stinepike

Reputation: 54672

If I am not wrong your are trying to save global variables without extending Application. If so you can do two things

if you don't need any context then you ca simply use a class with static members like this

public class ApplicationState {
    public static boolean get() {
        return b;
    }

    public static void set(boolean a) {
        b = a;
    }

    private static boolean b;
}

And if you need a context but you don't want to extend Application you can use

Public class ApplicationState {
    private Context context;
    private static ApplicationState instance;

    private ApplicationState(Context context) {
        this.context = context;


    public static ApplicationState getInstance(Context context) {
        if (instance == null) {
            instance = new ApplicationState(context);
        }
        return instance;
    }

    public void someMethod(){}
}

So you can call some method like this ApplicationState.getInstance(context).somemethod();

Upvotes: 6

Related Questions