Android SharedPreferences跟File

Android SharedPreferences和File
本讲内容:SharedPreferences 和 Android中的文件IO操作
1、SharedPreferences
2、Android中的文件IO操作

Android中进行数据共享和数据存储有多种方式,前面我们讲过使用Sqlite数据库的方式,今天我们讲一下SharedPreferences和文件读写操作方式。

一、SharedPreferences

SharedPreferences是一种轻量级的数据存储方式,学过Web开发的同学,可以想象它是一个小小的Cookie。它可以用键值对的方式把简单数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/包名/shared_prefs/)自己定义的xml文件中。下面我们用一个记录音乐播放进度的例子来学习SharedPreferences的使用。

1、建立一个新的项目 Lesson19_HelloSharedPreferences , Activity名字叫 MainHelloSharedPreferences.java

2、建立一个MusicService.java的Service,代码如下:

view sourceprint?01 package android.basic.lesson19; 

02   

03 import android.app.Service; 

04 import android.content.Context; 

05 import android.content.Intent; 

06 import android.content.SharedPreferences; 

07 import android.media.MediaPlayer; 

08 import android.os.IBinder; 

09 import android.widget.Toast; 

10   

11 public class MusicService extends Service { 

12   

13     //定义MediaPlayer播放器变量 

14     MediaPlayer mPlayer = new MediaPlayer(); 

15   

16     @Override

17     public void onCreate() { 

18         Toast.makeText(getApplicationContext(), "Service onCreate()", Toast.LENGTH_LONG).show(); 

19         //创建播放器 

20         mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.babayetu); 

21         //设置自动循环 

22         mPlayer.setLooping(true); 

23     } 

24   

25     @Override

26     public IBinder onBind(Intent intent) { 

27         Toast.makeText(getApplicationContext(), "Service onBind()", Toast.LENGTH_LONG).show(); 

28         //获得SharedPreferences对象 

29         SharedPreferences preferences = this.getSharedPreferences("MusicCurrentPosition",Context.MODE_WORLD_WRITEABLE); 

30         //播放器跳转到上一次播放的进度 

31         mPlayer.seekTo(preferences.getInt("CurrentPosition", 0)); 

32         //开始播放 

33         mPlayer.start(); 

34         return null; 

35     } 

36   

37     @Override

38     public boolean onUnbind(Intent intent){ 

39         Toast.makeText(getApplicationContext(), "Service onUnbind()", Toast.LENGTH_LONG).show(); 

40         //获得SharedPreferences对象 

41         SharedPreferences preferences = this.getSharedPreferences("MusicCurrentPosition",Context.MODE_WORLD_WRITEABLE); 

42         Toast.makeText(getApplicationContext(), "CurrentPosition="+mPlayer.getCurrentPosition(), Toast.LENGTH_LONG).show(); 

43         //获得editor对象,写入一个整数到SharePreferences中,记住要用commit()提交,否则不会实现写入操作 

44         preferences.edit().putInt("CurrentPosition",mPlayer.getCurrentPosition()).commit(); 

45         mPlayer.stop(); 

46         return false; 

47     } 

48 }

3、更改AndroidManifest.xml内容如下:

view sourceprint?01 <?xml version="1.0" encoding="utf-8"?> 

02 <MANIFEST package="android.basic.lesson19" xmlns:android="http://schemas.android.com/apk/res/android" android:versioncode="1" android:versionname="1.0"> 

03     <APPLICATION android:label="@string/app_name" android:icon="@drawable/icon"> 

04         <ACTIVITY android:label="@string/app_name" android:name=".MainHelloSharedPreferences"> 

05             <INTENT -filter> 

06                 <ACTION android:name="android.intent.action.MAIN" /> 

07                 <CATEGORY android:name="android.intent.category.LAUNCHER" /> 

08             </INTENT> 

09         </ACTIVITY> 

10         <SERVICE android:name=".MusicService" android:enabled="true"> 

11         </SERVICE> 

12     </APPLICATION> 

13     <USES -sdk android:minsdkversion="8" /> 

14   

15 </MANIFEST>

4、res/layout/mail.xml的内容如下:

view sourceprint?01 <?xml version="1.0" encoding="utf-8"?> 

02 <LINEARLAYOUT xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical"> 

03     <TEXTVIEW android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/TextView01" android:text="SharedPreferences的使用" android:textsize="20sp"> 

04     </TEXTVIEW> 

05   

06 <BUTTON android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button01" android:text="绑定音乐播放服务" android:textsize="20sp" android:layout_margintop="10dp"> 

07 </BUTTON> 

08 <BUTTON android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button02" android:text="解绑定音乐播放服务" android:textsize="20sp" android:layout_margintop="10dp"> 

09 </BUTTON> 

10 </LINEARLAYOUT>

5、MainHelloSharedPreferences.java的内容如下:

view sourceprint?01 package android.basic.lesson19; 

02   

03 import android.app.Activity; 

04 import android.content.ComponentName; 

05 import android.content.Context; 

06 import android.content.Intent; 

07 import android.content.ServiceConnection; 

08 import android.os.Bundle; 

09 import android.os.IBinder; 

10 import android.view.View; 

11 import android.view.View.OnClickListener; 

12 import android.widget.Button; 

13 import android.widget.Toast; 

14   

15 public class MainHelloSharedPreferences extends Activity { 

16     /** Called when the activity is first created. */

17     @Override

18     public void onCreate(Bundle savedInstanceState) { 

19         super.onCreate(savedInstanceState); 

20         setContentView(R.layout.main); 

21   

22         //定义UI组件 

23         Button b1 = (Button) findViewById(R.id.Button01); 

24         Button b2 = (Button) findViewById(R.id.Button02); 

25   

26         //定义ServiceConnection对象 

27         final ServiceConnection conn = new ServiceConnection() { 

28   

29             @Override

30             public void onServiceConnected(ComponentName name, IBinder service) { 

31             } 

32   

33             @Override

34             public void onServiceDisconnected(ComponentName name) { 

35             } 

36         }; 

37   

38         //定义按钮的单击监听器 

39         OnClickListener ocl = new OnClickListener() { 

40             @Override

41             public void onClick(View v) { 

42                 Intent intent = new Intent(MainHelloSharedPreferences.this, 

43                         android.basic.lesson19.MusicService.class); 

44                 switch (v.getId()) { 

45                 case R.id.Button01: 

46                     Toast.makeText(getApplicationContext(), "Button01 onClick", Toast.LENGTH_LONG).show(); 

47                     //绑定服务 

48                     bindService(intent,conn,Context.BIND_AUTO_CREATE); 

49                     break; 

50                 case R.id.Button02: 

51                     Toast.makeText(getApplicationContext(), "Button02 onClick", Toast.LENGTH_LONG).show(); 

52                     //取消绑定 

53                     unbindService(conn); 

54                     break; 

55                 } 

56             } 

57         }; 

58   

59         //绑定单击监听器 

60         b1.setOnClickListener(ocl); 

61         b2.setOnClickListener(ocl); 

62   

63     } 

64 }

6、运行程序,查看运行情况:





查看 File Explorer,在/data/data/android.basic.lesson19/shared_prefs/目录下有一个MusicCurrentPosition.xml文件,点击右上角的按钮 pull a file from the device,可以把这个xml文拷贝出来



7、查看MusicCurrentPosition.xml的内容,可以看到音乐播放进度的数据存贮在这个xml中

view sourceprint?1 <?xml version='1.0' encoding='utf-8' standalone='yes' ?> 

2 <MAP> 

3 <INT value="15177" name="CurrentPosition" /> 

4 </MAP>

兴趣的同学可以尝试一下,在Activity中增加一个按钮,点击以后把SharedPreference中的播放进度数据取出来,显示在另一个文本框Textview02里,我在这里把最后的运行结果图放这里,代码你们可以自己练习着敲出来,从中体会Share的意思,是不是在同一个APK中不同的组件之间都可以去访问这个共享的持久化数据?从这一点上说是不是有点像是Cookie?