打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
第十八讲: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,代码如下:
  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.                                         break;
  48.                                 }
  49.                         }
  50.                 };

  51.                 //绑定单击监听器
  52.                 b1.setOnClickListener(ocl);
  53.                 b2.setOnClickListener(ocl);

  54.         }
  55. }
复制代码
6、运行程序,查看运行情况:


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

7、查看MusicCurrentPosition.xml的内容,可以看到音乐播放进度的数据存贮在这个xml中
  1. <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  2. <map>
  3. <int name="CurrentPosition" value="15177">
  4. </int></map>
复制代码
兴趣的同学可以尝试一下,在Activity中增加一个按钮,点击以后把SharedPreference中的播放进度数据取出来,显示在另一个文本框Textview02里,我在这里把最后的运行结果图放这里,代码你们可以自己练习着敲出来,从中体会Share的意思,是不是在同一个APK中不同的组件之间都可以去访问这个共享的持久化数据?从这一点上说是不是有点像是Cookie?

二、Android中的文件IO操作(待续)

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android网络收音机项目
Android Service Tutorial
Android 广播接受者
编写安卓无界面后台程序 开机自启动服务
activity、service、BroadcastReceive之间如何互相通讯,并取回相应的结果
Android Service Test——简单测试例子
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服