Api demo源码学习(7)--App/Activity/Persistent State
在智能手机的使用过程中常常会碰到这样的情况,比如你正在写一条短信,突然一个电话打进来,等你电话接完回来重新写短信的时候,如果发现原来辛辛苦苦写的短信全都没了,那你一定会发狂的。所以这些临时数据我们需要暂时保存起来,Android提供了SharedPreferences的存储机制用来储存这一类数据。
一般临时数据的存储操作放在onPause()中进行,恢复数据的操作就放在onResume()中进行。
View Code
通过DDMS工具可以看到临时保存的数据在 手机文件系统的/data/data/#你的包名#/shared_prefs/类名.xml 中。1 public class PersistentStateActivity extends Activity {
2 /** Called when the activity is first created. */
3 private EditText mSaved;
4 private TextView mView;
5
6 @Override
7 public void onCreate(Bundle savedInstanceState) {
8 super.onCreate(savedInstanceState);
9 setContentView(R.layout.save_restore_state);
10
11 mView = (TextView) findViewById(R.id.msg);
12 mView.setText(R.string.persistent_msg);
13 mSaved = (EditText)findViewById(R.id.saved);
14 }
15
16 @Override
17 protected void onResume() {
18 // TODO Auto-generated method stub
19 super.onResume();
20
21 SharedPreferences prefs = getPreferences(0);
22 String restoredText = prefs.getString("text", null);
23 if (restoredText != null) {
24 mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
25
26 int selectionStart = prefs.getInt("selection-start", -1);
27 int selectionEnd = prefs.getInt("selection-end", -1);
28 if (selectionStart != -1 && selectionEnd != -1) {
29 mSaved.setSelection(selectionStart, selectionEnd);
30 }
31 }
32 }
33
34 @Override
35 protected void onPause() {
36 // TODO Auto-generated method stub
37 super.onPause();
38
39 SharedPreferences.Editor editor = getPreferences(0).edit();
40 editor.putString("text", mSaved.getText().toString());
41 editor.putInt("selection-start", mSaved.getSelectionStart());
42 editor.putInt("selection-end", mSaved.getSelectionEnd());
43 editor.commit();
44 }
45 }