简体   繁体   中英

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?

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

Yes, you are right. If you will create a static variable it will be alive till your applications is running when it will be cleared from background your variable value will be null.

For that there are 2 possibilities that can solve your problem:

  1. Use shared-preferences but you will lose your value if the user go to settings and from there user clear app data

  2. User Sqlite db you will also lose your data when the user clear app data or user uninstall the application.

use 2 if your data is big other wise 1 is best.Tanks.

When You install your app then you have to store value in shardeprefrence is better option for you

Use shared preference

private static final String _KEY = "app_unique_key";
private static final String _PREFERENCE = "preference";
public void saveKey(String appKey) {
    SharedPreferences preferences = getSharedPreferences(_PREFERENCE, Context.MODE_PRIVATE);
    SharedPreferences.Editor preferenceEditor = preferences.edit();
    preferenceEditor.putString(_KEY, appKey);
    preferenceEditor.apply();
}

public String getAppKey() {
    SharedPreferences preferences = getSharedPreferences(_PREFERENCE, Context.MODE_PRIVATE);
    return preferences.getString(_KEY, null);
}

I think you need use a SharedPreferences vars... This methods only use for String values if you need to save int,floats, etc... you can create a different methods or just apply code when you need it. I think the best wayt is have in methods because you don't need to repeat code and to control values it's more easy... See the below code to know use sharedPreferences:

//Declaration of variables
//This var is name from file of shared preferences, you can save a different files for SharedPreferences
public String StartConfig_File = "sharedPref_StartConfig_File";

//And this one is a SharedPreference var from my StartConfig_File
public String userRemembered = "userRemembered";


//Method to get String from SharedPreference
public String Get_SharedPreferences(Context context, String sharedPref_File,String key_name){

    //Declaration of variables
    SharedPreferences sharedPref = context.getSharedPreferences(sharedPref_File, Context.MODE_PRIVATE);
    String result = sharedPref.getString(key_name, null);

    return result;
}

//Method to set String SharedPreference
public void Set_SharedPreferences(Context context,String sharedPref_File, String key_name,String key_value){

    //Declaration of variables
    SharedPreferences sharedPref = context.getSharedPreferences(sharedPref_File,Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();

    editor.putString(key_name,key_value);

    editor.commit();
}

And below have a sample to call this methods:

//generalMethods is class where I have sharedPreferences methods! Change for your class...

//Initialize values from SharedPreference
generalMethods.Set_SharedPreferences(getActivity(),generalMethods.StartConfig_File,generalMethods.userRemembered ,"MyUser");

//Get value from SharedPreference
String result = generalMethods.Get_SharedPreferences(getActivity(), generalMethods.StartConfig_File, generalMethods.userRemembered );

This vars only disappear when app is uninstalled, you can get this values always if you have acces to context... Tell me if I helped you and good programming!

First of all, I would create the String inside the Application. To do this, you need to create a class that extends the android.app.Application , put the class name inside the AndroidManifest application tag and then overrides the onCreate() with this

public void onCreate() {
    super.onCreate();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!prefs.containsKey("MY_KEY")) {
        String random = generateYourRandomKey();
        prefs.edit().putString("MY_KEY", random).apply();
    }
}

then in every Activity/Service/BrodcastReceiver of your project you can read the value using

String random = PreferenceManager.getDefaultSharedPreferences(aContext).getString("MY_KEY");

where aContext is the context of the Activity/Service and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM