- 浏览: 7745 次
- 性别:
- 来自: 广州
最新评论
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?
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?
发表评论
-
msql分区
2014-06-12 18:03 546一、什么是表分区 通俗地讲表分区是将一大表,根据条件分割成若干 ... -
java中使用redis
2013-01-10 15:00 729Redis本质上是一个Key-Value类型的内存数据库。 ... -
二.redis 数据类型
2013-01-10 14:33 5111. keys redis本质上一个key ... -
一.redis 环境搭建
2013-01-10 14:28 5791.简介 redis是一个开源的key-value数据库。它又 ... -
Netty多线程服务器与客户端
2012-09-25 13:03 941发此篇博客的目的是,如果有网络通讯方面的大牛看到,希望能给与一 ... -
Netty初步之hello world
2012-09-25 13:00 737Java的网络操作一直比较复杂,虽然说在加入NIO之后简单了些 ... -
Apache MINA 服务端与客户端实例
2012-09-25 11:49 686Apache的MINA是一个被用来 ... -
XMPP的客户端连接实例
2012-09-21 17:16 669连接,并向一个用户发送信息,只需要三行代码: XMPPCon ... -
Mina之IoBuffer
2012-09-21 11:33 938原文:http://mina.apache.org/iobuf ... -
Apache MINA 快速入门
2012-09-21 11:20 6421。介绍 Apache MINA 是一个网络应用框架,有助于 ...
相关推荐
Simple Android SharedPreferences wrapper. Repository Add this in your root build.gradle file (not your module build.gradle file): allprojects { repositories { ... maven { url ...
第十八讲:Android SharedPreferences和File 第十九讲:Android Notification的使用入门 第二十讲:Content Provider 使用入门 第二十一讲:Broadcast Receiver 使用入门 第二十二讲:AIDL和远程Service调用 ...
Android自学笔记-8-Android数据存储1:文件、SharedPreferences和获取sd卡信息
Android项目开发中使用的数据存储方式有:网络存储、sqlite存储、File存储和SharedPreferences存储,四种存储方式对应的Demo别人是NetworkDemo、SqliteDemo、FileDemo和SharedPreferencesDemo,根据应用的场景选择...
android的三种存储demo SharedPreferences存储 File存储 SQLite存储
申明人(签名): 实验报告评语与评分: 评阅老师签名: 一、实验名称:Android数据存储与IO 二、实验日期:2014/11/13 三、实验目的: 1、掌握SharedPreferences的存储数据的格式及位置,能够读写其他应用程序的...
e /SharedPreferences/File详解 多媒体Audio/Video/Camera 详解 Android进阶高级:蓝牙/WIFI SMS/MMS 应用实现 深层次解析GPS原理,实现LocationManager/LocationProvider 进行定位/跟踪/查找/趋近警告以及...
对Android的界面设计有详细的代码...使用的登录界面非常精美,具有利用价值,有Android的各种颜色值代表什么颜色的介绍,使用SharedPreferences和file两种存储方式,ListView具有两行显示功能,在eclipse下可直接使用!
介绍了android总三种数据存储的方式: 1 SharedPreferences 2 File输入流输出流 3 SQLite 数据库 增删改查
It allows you to save any type or list in the sharedpreferences and retrieve it in convenient way. Installation Gradle Add jitpack.io to your root gradle file (project level) : allprojects {...
android 四种存储方式 file SharedPreferences ContentProvider SQLite的简单使用示例
SharedPreferencesUtils SharedPreferences Unility Class ShellUtils Shell Unility Class StringUtils String Unility Class SystemUtils System Unility Class TelephonyUtils Telephony Unility Class ...
对Android的界面设计有详细的代码...使用的登录界面非常精美,具有利用价值,有Android的各种颜色值代表什么颜色的介绍,使用SharedPreferences和file两种存储方式,ListView具有两行显示功能,在eclipse下可直接使用!
2.2 系统结构图和流程图 - 10 - 2.3 系统界面需求 - 11 - 2.4 系统性能需求 - 12 - 2.5 运行环境需求 - 12 - 第三章 Android数据库设计 - 13 - 3.1 数据库及字段属性设计 - 13 - 3.1.1 字段设计(表、图) - 13 - ...
Optional persistent cookie store, saves cookies into your app's SharedPreferences Examples For inspiration and testing on device we've provided Sample Application. See individual samples here on ...
2.2 系统结构图和流程图 - 10 - 2.3 系统界面需求 - 11 - 2.4 系统性能需求 - 12 - 2.5 运行环境需求 - 12 - 第三章 Android数据库设计 - 13 - 3.1 数据库及字段属性设计 - 13 - 3.1.1 字段设计(表、图) - 13 - ...
1.1 Android的发展和历史 2 1.1.1 Android的发展和简介 2 1.1.2 Android平台架构及特性 3 1.2 搭建Android开发环境 5 1.2.1 下载和安装Android SDK 5 1.2.2 安装Eclipse和ADT插件 7 1.3 Android常用...
8.2、File存储:openFileOutput和openFileInput; 读写SD卡文件; 8.3、SQLite数据库:SQL语句; SQLiteDatabase; SQLiteOpenHelper; sqlite3 tools; 8.4、手势(Gesture): 8.5、自动朗读(TTS): 8.6、网络存储...
SharedPreferences on Android stores all of your values in "plain text", simply protected by the user-restricted file system on Android. If you gain root access to an Android device you have full read/...