Android SharedPreferences

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

mode:是指定读写方式,其值有三种,分别为:

Context.MODE_PRIVATE:指定该SharedPreferences数据只能被本应用程序读、写

Context.MODE_WORLD_READABLE:指定该SharedPreferences数据能被其他应用程序读,但不能写

Context.MODE_WORLD_WRITEABLE:指定该SharedPreferences数据能被其他应用程序读写。

插入数据:

调用Editor.putxxxx方法,两个参数分别为键和值。

如:

SharedPreferencessharedPreferences= getSharedPreferences("itcast",Context.MODE_PRIVATE);

Editoreditor= sharedPreferences.edit();//获取编辑器

editor.putString("name","播客");

editor.putInt("age",4);

editor.commit();//提交修改

获取数据:

调用Editor.getxxxx方法,两个参数分别为键和不存在指定键时的默认值。

如:

SharedPreferencessharedPreferences= getSharedPreferences("itcast",Context.MODE_PRIVATE);

//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值

Stringname = sharedPreferences.getString("name","");

intage = sharedPreferences.getInt("age",1);

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。如:有个<packagename>cn.itcast.action的应用使用下面语句创建了preference

getSharedPreferences("itcast",Context.MODE_WORLD_READABLE);

其他应用要访问上面应用的preference首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference

ContextotherAppsContext= createPackageContext("cn.itcast.action",Context.CONTEXT_IGNORE_SECURITY);

SharedPreferencessharedPreferences= otherAppsContext.getSharedPreferences("itcast",Context.MODE_WORLD_READABLE);

Stringname = sharedPreferences.getString("name","");

intage = sharedPreferences.getInt("age",0);

如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件,如:

File xmlFile =new File(“/data/data/<package name>/shared_prefs/itcast.xml”);//<packagename>应替换成应用的包名

然后再使用SAX/DOM/PULL方法解析即可

删除数据:
调用Editor.remove方法,参数为指定的键。
清空所有数据:
调用Editor.clear方法
上述所有方法调用都要执行Editor.commit方法来提交。

一、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,代码如下:

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内容如下:

01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest android:versionname="1.0" android:versioncode="1"xmlns:android="http://schemas.android.com/apk/res/android"package="android.basic.lesson19">
03     <application android:icon="@drawable/icon" android:label="@string/app_name">
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             </category></action></intent>
09         </activity>
10         <service android:name=".MusicService" android:enabled="true">
11         </service>
12     </application>
13     <uses android:minsdkversion="8" -sdk="">
14  
15 </uses></manifest>

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

01 <?xml version="1.0" encoding="utf-8"?>
02 <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent">
03     <textview android:layout_width="wrap_content"android:layout_height="wrap_content" android:textsize="20sp"android:text="SharedPreferences的使用" android:id="@+id/TextView01">
04     </textview>
05  
06 <button android:layout_width="wrap_content" android:layout_height="wrap_content"android:textsize="20sp" android:text="绑定音乐播放服务" android:id="@+id/Button01"android:layout_margintop="10dp">
07 </button>
08 <button android:layout_width="wrap_content" android:layout_height="wrap_content"android:textsize="20sp" android:text="解绑定音乐播放服务" android:id="@+id/Button02"android:layout_margintop="10dp">
09 </button>
10 </linearlayout>

5、MainHelloSharedPreferences.java的内容如下:

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、运行程序,查看运行情况:

image

image

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

MC~OMM~8XOFGC$YYMS$S$KL

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?

image

转载 http://android.yaohuiji.com/archives/672
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值