Using Shared Preferences

来源:互联网 发布:arttemplate.js官网 编辑:程序博客网 时间:2024/06/05 18:48

 

SharedPreferences类类似windows下的ini文件,用于存储一些配置信息。

The SharedPreferences class provides a general framework that allows youto save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, andstrings. This data will persist across user sessions (even if your application is killed).

To get a SharedPreferences object for your application, use one oftwo methods:

  • getSharedPreferences() - Use this if you need multiple preferences files identified by name,which you specify with the first parameter.
  • getPreferences() - Use this if you needonly one preferences file for your Activity. Because this will be the only preferences filefor your Activity, you don't supply a name.

To write values:

  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

Here is an example that saves a preference for silent keypress mode in acalculator:

public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
   @Override
protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);//提供文件名,可设置读写权限       // getPreferences(MODE_PRIVATE);   //不提供文件参数,默认为工程名。在工程的私有文件夹的share_prefs可找到相应的文件 boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); }

@Override protected void onStop(){ super.onStop(); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit(); }
}
原创粉丝点击