Search code examples
javaandroidsharedpreferencespersistence

Android - preserve value of variable through the lifecycle of an app


I have a mobile app which, once installed, must generate a random String that must be kept during its entire lifecycle till uninstalled.

I was thinking of using static variables, but as posted here, if I kill my application, the static variable will be null again and will be re-initialized.

What I need to do is create a random string during installation of the APK, and maintain its value while the application is installed, never mind whether it is killed or not.

Is there any way to achieve this?


Solution

  • You need to use SharedPreferences. The official tutorial for how to get and set a SharedPreference is here.