[Android储存]Shared Preferences

[Android存储]Shared Preferences[引用 http://developer.android.com/guide/topics/data/data-storage.ht

[Android存储]Shared Preferences
[引用 http://developer.android.com/guide/topics/data/data-storage.html#pref]
我们可以使用Shared Preferences来存储Key-Values对的私有数据,其中包括:booleans, floats, ints, longs, and strings.但是没有提供Object对象的存储。这些私有数据可以被持久的保存即使应用程序本身被关闭。

1)Shared Preferences提供了2个方法:
   a)getSharedPreferences(String name, int mode)
   当需要多个 preferences file时需要使用该方法通过名字来定义
   b)getPreferences(int mode)
   如果只需要使用一个preferences file无需使用名字
   c)mode的值:
   Activity.MODE_PRIVATE = 0x0000;
   where the created file can only be accessed by the calling application
   Activity.MODE_WORLD_READABLE = 0x0001;
   Allow all other applications to have read access
   Activity.MODE_WORLD_WRITEABLE = 0x0002;
   Allow all other applications to have write access
  
2)写入值到preferences file
   a)call edit() to get a SharedPreferences.Editor.
   b)Add values with methods such as putBoolean() and putString().
   c)Commit the new values with commit()

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, 0);       // If only store one preferences file use below method       // SharedPreferences settings = getSharedPreferences(0);       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, 0);      // If only store one preferences file use below method      SharedPreferences settings = getSharedPreferences([b][/b]0);      SharedPreferences.Editor editor = settings.edit();      editor.putBoolean("silentMode", mSilentMode);      // Commit the edits!      editor.commit();    }}