Activity的持久化状态是用getPreferences(int)方法返回的SharedPreferences对象来管理的,这个对象允许使用跟Activity关联的name/value对来获取和编辑Activity私有的状态。这个方法内部只是简单的调用getSharedPreferences(String, int)方法,其中的String参数使用Activity的类名作为偏好的名字。
方法声明:
Public SharedPreferences getPreferences(int mode)
参数说明:
mode:操作模式,有三种可能的选择:
MODE_PRIVATE:默认的操作,创建只能被调用应用程序访问的文件(或者是共享相同用户名的所有应用程序),常量值:0(0x00000000)
MODE_WORLD_READABLE:允许其他应用程序对创建的文件有读取的访问权限。常量值:1(0x00000001)
MODE_WORLD_WRITEABLE:允许其他的应用程序对创建的文件有写的访问权限。常量值:2(0x00000002)
返回值:返回一个能够用于获取或编辑偏好值的SharedPreferences实例对象。
例如:
@Override
protectedvoid onResume(){
super.onResume();
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if(restoredText != null){
mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if(selectionStart != -1 && selectionEnd != -1){
mSaved.setSelection(selectionStart, selectionEnd);
}
}
}
@Override
protectedvoid onPause(){
super.onPause();
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("text", mSaved.getText().toString());
editor.putInt("selection-start", mSaved.getSelectionStart());
editor.putInt("selection-end", mSaved.getSelectionEnd());
editor.commit();
}