Question

I have a doubt regarding the behavior of Android with a static variable created in an Activity. I created a static boolean variable which is true if the running device API is < 11 and false if not.

public static boolean apiLower11;

i assign a value to it in onCreate (just now i thinked why i didn't do directly public static boolean apiLower11 = !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);) of my MainActivity which is the activity where my application start. This variable is used in other Activities too (it's the important part).

Now starts my question:

Suppose that one day you can open the application by starting another activity (via a notification?) without going through the main activity, what is the value of my static variable? The main activity has not been created then has not received any value right?

What if the Main Activity is destroyed while the user is browsing my application (I know, Android kills other process not what the user is using..) but is possibile this kind of scenario? And what will happen to my static variable?

As far as i know: static variables are created when the class is loaded so which will remains alive until the classloader is alive. If i put the

apiLower11 = !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);

inside a static block i will not have this problem?

The value is assigned one time and i avoid this assign every time the onCreate of the activity is called.

I think as alternative to use a class which extends Application and put this variable so it should be alive during the entire life cycle of the application.

Anyway, the big mistake i could see by himself here is the wrong thing to give the value to the variable in the onCreate method instead of static block

Was it helpful?

Solution

If the static variable has not been initialized,it will get a default value(apiLower11 will be false).

so

Suppose that one day you can open the application by starting another activity (via a notification?) without going through the main activity, what is the value of my static variable? The main activity has not been created then has not received any value right?

The answer is your static variable apiLower11 is false.

apiLower11 = !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB);inside a static block i will not have this problem?

The answer is yes,you can do it,because the static block will be executed just after the ClassLoader loaded the MainActivity.class

OTHER TIPS

You could pull this out into another class:

public class ApiLevel {
    public static boolean isLowerThan11() {
         return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
    }
}

Now, instead of calling MainActivity.apiLower11 when you need to check, you call ApiLevel.isLowerThan11().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top