Home > Net >  Should you make a variable static to protect it from getting deleted over the long term?
Should you make a variable static to protect it from getting deleted over the long term?

Time:04-03

Say your android app has an accessibility service with a variable that it should always be able to use. The variable in this case is called sharedPreferences. It gets assigned a value only once in its lifetime in the onServiceConnected(). Will this non-static variable retain its value after 5 months of not being touched or will it somehow get emptied? Am I misunderstanding what static and non-static is?

public class MyAccessibilityService extends AccessibilityService {

    SharedPreferences sharedPreferences;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();

        AccessibilityServiceInfo configuration = new AccessibilityServiceInfo();
        configuration.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
        configuration.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        setServiceInfo(configuration);

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
    
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            if (some kind of rare event) {
                String string = sharedPreferences.getString("key", "default");
                ...
            }
        }
    }

}

CodePudding user response:

Static just means the variable is not tied to a specific instance of the class - if your service/app/task is stopped the static variable will still be garbage collected. If you make a non-static class member variable and set it in onServiceConnected you can be guaranteed that it will be valid for any method called in that class after onServiceConnected.

Even if the service is stopped and restarted, once it calls onServiceConnected on the new instance the class variable will be valid again.

  • Related