本讲内容: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,代码如下:
  1. package android.basic.lesson19;


  2. import android.app.Service;

  3. import android.content.Context;

  4. import android.content.Intent;

  5. import android.content.SharedPreferences;

  6. import android.media.MediaPlayer;

  7. import android.os.IBinder;

  8. import android.widget.Toast;


  9. public class MusicService extends Service {


  10.        //定义MediaPlayer播放器变量

  11.        MediaPlayer mPlayer = new MediaPlayer();


  12.        @Override

  13.        public void onCreate() {

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

  15.                //创建播放器

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

  17.                //设置自动循环

  18.                mPlayer.setLooping(true);

  19.        }


  20.        @Override

  21.        public IBinder onBind(Intent intent) {

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

  23.                //获得SharedPreferences对象

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

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

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

  27.                //开始播放

  28.                mPlayer.start();

  29.                return null;

  30.        }


  31.        @Override

  32.        public boolean onUnbind(Intent intent){

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

  34.                //获得SharedPreferences对象

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

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

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

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

  39.                mPlayer.stop();

  40.                return false;

  41.        }

  42. }


3、更改AndroidManifest.xml内容如下:
  1. <?xml version="1.0" encoding="utf-8"?>

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

  3.    <application android:icon="@drawable/icon" android:label="@string/app_name">

  4.        <activity android:label="@string/app_name" android:name=".MainHelloSharedPreferences">

  5.            <intent -filter="">

  6.                <action android:name="android.intent.action.MAIN">

  7.                <category android:name="android.intent.category.LAUNCHER">

  8.            </category></action></intent>

  9.        </activity>

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

  11.            </service>

  12.    </application>

  13.    <uses android:minsdkversion="8" -sdk="">


  14. </uses></manifest>


4、res/layout/mail.xml的内容如下:
  1. <?xml version="1.0" encoding="utf-8"?>

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

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

  4.        </textview>


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

  6. </button>

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

  8. </button>

  9. </linearlayout>


5、MainHelloSharedPreferences.java的内容如下:
  1. package android.basic.lesson19;


  2. import android.app.Activity;

  3. import android.content.ComponentName;

  4. import android.content.Context;

  5. import android.content.Intent;

  6. import android.content.ServiceConnection;

  7. import android.os.Bundle;

  8. import android.os.IBinder;

  9. import android.view.View;

  10. import android.view.View.OnClickListener;

  11. import android.widget.Button;

  12. import android.widget.Toast;


  13. public class MainHelloSharedPreferences extends Activity {

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

  15.        @Override

  16.        public void onCreate(Bundle savedInstanceState) {

  17.                super.onCreate(savedInstanceState);

  18.                setContentView(R.layout.main);


  19.                //定义UI组件

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

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


  22.                //定义ServiceConnection对象

  23.                final ServiceConnection conn = new ServiceConnection() {


  24.                        @Override

  25.                        public void onServiceConnected(ComponentName name, IBinder service) {

  26.                        }


  27.                        @Override

  28.                        public void onServiceDisconnected(ComponentName name) {

  29.                        }

  30.                };


  31.                //定义按钮的单击监听器

  32.                OnClickListener ocl = new OnClickListener() {

  33.                        @Override

  34.                        public void onClick(View v) {

  35.                                Intent intent = new Intent(MainHelloSharedPreferences.this,

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

  37.                                switch (v.getId()) {

  38.                                case R.id.Button01:

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

  40.                                        //绑定服务

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

  42.                                        break;

  43.                                case R.id.Button02:

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

  45.                                        //取消绑定

  46.                                        unbindService(conn);

  47.