[引用 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)[b]getSharedPreferences(String name, int mode)[/b]
当需要多个 preferences file时需要使用该方法通过名字来定义
b)[b]getPreferences(int mode)[/b]
如果只需要使用一个preferences file无需使用名字
c)mode的值:
[b]Activity.MODE_PRIVATE = 0x0000;[/b]
[color=green]where the created file can only be accessed by the calling application[/color]
[b]Activity.MODE_WORLD_READABLE = 0x0001;[/b]
[color=green]Allow all other applications to have read access[/color]
[b]Activity.MODE_WORLD_WRITEABLE = 0x0002;[/b]
[color=green]Allow all other applications to have write access[/color]
2)写入值到preferences file
a)call [b]edit()[/b] to get a SharedPreferences.Editor.
b)Add values with methods such as [b]putBoolean()[/b] and [b]putString()[/b].
c)Commit the new values with [b]commit()[/b]
我们可以使用Shared Preferences来存储Key-Values对的私有数据,其中包括:booleans, floats, ints, longs, and strings.但是没有提供Object对象的存储。这些私有数据可以被持久的保存即使应用程序本身被关闭。
1)Shared Preferences提供了2个方法:
a)[b]getSharedPreferences(String name, int mode)[/b]
当需要多个 preferences file时需要使用该方法通过名字来定义
b)[b]getPreferences(int mode)[/b]
如果只需要使用一个preferences file无需使用名字
c)mode的值:
[b]Activity.MODE_PRIVATE = 0x0000;[/b]
[color=green]where the created file can only be accessed by the calling application[/color]
[b]Activity.MODE_WORLD_READABLE = 0x0001;[/b]
[color=green]Allow all other applications to have read access[/color]
[b]Activity.MODE_WORLD_WRITEABLE = 0x0002;[/b]
[color=green]Allow all other applications to have write access[/color]
2)写入值到preferences file
a)call [b]edit()[/b] to get a SharedPreferences.Editor.
b)Add values with methods such as [b]putBoolean()[/b] and [b]putString()[/b].
c)Commit the new values with [b]commit()[/b]
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();
}
}