【起航计划 008】2015 起航计划 Android APIDemo的魔鬼步伐 07 App->Activity->Persistent State 保存状态 SharedPreferences onPause onResume

Android 提供了多种存储数据的方法,其中最简单的是使用Shared Preferences. Shared Preferences 可以存储 Key/value 对,Shared Preferences 支持存取 boolean, float ,long ,integer, string ,最常用的使用Shared Preferences是用来存储一些应用偏好。此外的一个方法是使用onSaveInstanceState(),这是特别用来保存UI 状态的。

此外的一个方法是使用onSaveInstanceState(),这是特别用来保存UI 状态的。

App->Activity->Persistent State 使用了Shared Preferences来保持部分UI状态(TextView的值)。

创建或是修改Shared Preferences,使用getSharedPreferences(String name, int mode)方法。Shared Preferences 用于单个Application不同Activity之间共享一些数据,但不能用于不同Application之间共享数据。

SharedPreferences.Editor 用来给Shared Preferences添加数据: editor.putXXX(key,value):

    /**
     * Any time we are paused we need to save away the current state, so it
     * will be restored correctly when we are resumed.
     */
    @Override
    protected void onPause() {
        super.onPause();

        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("text", mSaved.getText().toString());
        editor.putInt("selection-start", mSaved.getSelectionStart());
        editor.putInt("selection-end", mSaved.getSelectionEnd());
        editor.commit();
    }

读取Shared Preference: pref.getXXX(key)

    /**
     * Upon being resumed we can retrieve the current state.  This allows us
     * to update the state if it was changed at any time while paused.
     */
    @Override
    protected void onResume() {
        super.onResume();

        SharedPreferences prefs = getPreferences(0); 
        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);
            }
        }
    }

【起航计划 008】2015 起航计划 Android APIDemo的魔鬼步伐 07 App->Activity->Persistent State 保存状态 SharedPreferences onPause onResume

Persistent State 演示了如何使用Shared Preferences在Activity 恢复时保持EditText的内容。 单是更一般的方法是使用onSaveInstanceState.