Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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");
                ...
            }
        }
    }

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading