1./TestSharedPreferences/res/layout/main.xml:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="fill_parent"
5 android:layout_height="fill_parent"
6 >
7 <TextView
8 android:id="@+id/textview01"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:text="@string/hello"
12 />
13 </LinearLayout>
2. TestSharedPreferencesActivity:
1 import android.app.Activity;
2 import android.content.SharedPreferences;
3 import android.os.Bundle;
4 import android.view.KeyEvent;
5 import android.widget.TextView;
6
7 public class TestSharedPreferencesActivity extends Activity
8 {
9 private TextView mTextView01;
10
11 private boolean mbMusic = false;
12
13 // private MIDIPlayer
14 @Override
15 public void onCreate(Bundle savedInstanceState)
16 {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.main);
19 mTextView01 = (TextView) findViewById(R.id.textview01);
20 /**
21 * 装载数据
22 */
23 // 获得活动的Preferences对象
24 SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
25 // 取得值
26 mbMusic = settings.getBoolean("bmusic", false);
27 if (mbMusic)
28 {
29 mTextView01.setText("当前音乐状态:开");
30 mbMusic = true;
31 }
32 else
33 {
34 mTextView01.setText("当前音乐状态:关");
35 }
36 }
37
38 @Override
39 public boolean onKeyDown(int keyCode, KeyEvent event)
40 {
41 switch (keyCode)
42 {
43 case KeyEvent.KEYCODE_DPAD_DOWN:
44 mTextView01.setText("当前音乐状态:关");
45 mbMusic = false;
46 break;
47 case KeyEvent.KEYCODE_DPAD_UP:
48 mTextView01.setText("当前音乐状态:开");
49 mbMusic = true;
50 break;
51 }
52 return true;
53 }
54
55 @Override
56 public boolean onKeyUp(int keyCode, KeyEvent event)
57 {
58 if (keyCode == KeyEvent.KEYCODE_BACK)
59 {
60 /**
61 * 退出应用程序时保存数据
62 */
63 // 取得活动的preferences对象
64 SharedPreferences uiState = getPreferences(0);
65 // 取得编辑对象
66 SharedPreferences.Editor editor = uiState.edit();
67 // 添加值
68 editor.putBoolean("bmusic", mbMusic);
69
70 // 提交保存
71 editor.commit();
72 if (mbMusic)
73 {
74 System.out.println("-----------------------");
75 }
76 this.finish();
77 return true;
78 }
79 return super.onKeyUp(keyCode, event);
80 }
81 }
3.TestSharedPreferencesActivity.xml:
每安装一个应用程序时,在/data/data目录下都会产生一个文件夹,如果这个应用程序中使用了Preferences,那么便会在该文件夹下产生一个shared_prefs文件夹,其中就是我们保存的数据。
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
- <map>
<boolean name="bmusic" value="false" />
</map>