问题
I have interpreted the following about SharedPreferences
and have a bit of doubt of what they are capable of. Here is what I found:
Android
SharedPreferences
are used for the globalization of a variable so that throughout the application we can useSharedPreferences
to store and retrieve data instead of defining static variables in one class and let the class be used to retrieve the variables throughout the app.
Can someone explain whether this is correct. If there are major differences that I'm missing please let me know. Thanks.
回答1:
When saving sharedpreferences, the android system just creates a new xml file in your app directory holding those values. So if your app gets killed those variables will be saved. And the variables are always readable from any activity because they are stored in a file.
When storing sharedpreferences you use a key (final static String) to access them later, maybe that key is what they mean when talking about static's
small example:
Static:
public static final String PREFS_NAME = "settings"
public static final String SILENT_MODE = "silentMode";
In any activity of your app:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(SILENT_MODE, false);
Edit from: http://developer.android.com/guide/topics/data/data-storage.html#pref
回答2:
You use SharedPreferences to save and retrieve any primitive data. Unlike the Static variables approach, this data will persist across user sessions even if your application is killed.
来源:https://stackoverflow.com/questions/12624671/how-does-sharedpreferences-differ-from-a-static-global-variable-of-one-class