Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 367
HalukO Avatar asked Dec 12 '22 15:12

HalukO


2 Answers

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;
    }
}
like image 157
Ryan Thomas Avatar answered Dec 14 '22 04:12

Ryan Thomas


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();

like image 37
stinepike Avatar answered Dec 14 '22 05:12

stinepike