Garbage collected variables

I have an android app. After a while, when the user leaves the application, running something else and returning to my application, the static variables in the application seem to be garbage collected.

In the walnut shell, I save the entered username / password when starting the application and save them in a static variable and use them to communicate with the server. I need to either find out when they are collected with garbage collected when the application is restarted (so that I redirect them to view in login mode) or not allow this class to be garbage collected. Ideas?

+4
source share
2 answers

One way to implement the second scenario is to implement your own class that inherits the application and specify it in your manifest. You can put your static variables in this class. Android will create one instance of this class when it starts your process, and this instance will be alive until the process is alive.

So, if you have a simple logical class in this class that indicates whether the signin action has been performed, now you have a reliable way to check at any time whether you should direct the user to login activity or try to use the username / password .

In addition, you can use one of the standard Android persistence components (shared preferences file, SQLLite, AccountManager, OBB, credential storage, etc.) to save credentials when the process restarts. However, please note that this raises a number of problems related to how to properly protect the saved copy of the user credentials in order to protect it from unauthorized access by other applications (especially on root phones).

+4
source

I suggest not trying to "prevent the collection of this garbage." Instead, work within the framework as intended.

(Not relevant to user authentication or credential management ...)

Android provides several options for storing data, indicated in http://developer.android.com/guide/topics/data/data-storage.html . For your situation, using preferences may be an acceptable, easy, easy-to-use option.

Also note that storing values ​​in Activity members can solve the problem if the application has an Activity using values. If so, then note that using onSaveInstanceState (Bundle) and onRestoreInstanceState (Bundle) may be ok.

+2
source

All Articles