您的位置:首页 > 其它

持久保存Activity的状态

2012-04-05 16:53 211 查看
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实例对象。

例如:

     /*
    
* 在Activity显示的时候恢复被挂起或销毁时保存的状态
    
* @see android.app.Activity#onResume()
    
*/
   
@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);
   
    }
   
}
   
}
     /*
    
* Activity被挂起或销毁时,保存当前的状态。
    
* @see android.app.Activity#onPause()
    
*/
   
@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();
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string null