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; |
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; |
11 | public class MusicService extends Service { |
14 | MediaPlayer mPlayer = new MediaPlayer(); |
17 | public void onCreate() { |
18 | Toast.makeText(getApplicationContext(), "Service onCreate()" , Toast.LENGTH_LONG).show(); |
20 | mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.babayetu); |
22 | mPlayer.setLooping( true ); |
26 | public IBinder onBind(Intent intent) { |
27 | Toast.makeText(getApplicationContext(), "Service onBind()" , Toast.LENGTH_LONG).show(); |
29 | SharedPreferences preferences = this .getSharedPreferences( "MusicCurrentPosition" ,Context.MODE_WORLD_WRITEABLE); |
31 | mPlayer.seekTo(preferences.getInt( "CurrentPosition" , 0 )); |
38 | public boolean onUnbind(Intent intent){ |
39 | Toast.makeText(getApplicationContext(), "Service onUnbind()" , Toast.LENGTH_LONG).show(); |
41 | SharedPreferences preferences = this .getSharedPreferences( "MusicCurrentPosition" ,Context.MODE_WORLD_WRITEABLE); |
42 | Toast.makeText(getApplicationContext(), "CurrentPosition=" +mPlayer.getCurrentPosition(), Toast.LENGTH_LONG).show(); |
44 | preferences.edit().putInt( "CurrentPosition" ,mPlayer.getCurrentPosition()).commit(); |
3、更改AndroidManifest.xml内容如下:
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
03 | < application android:icon = "@drawable/icon" android:label = "@string/app_name" > |
04 | < activity android:label = "@string/app_name" android:name = ".MainHelloSharedPreferences" > |
06 | < action android:name = "android.intent.action.MAIN" > |
07 | < category android:name = "android.intent.category.LAUNCHER" > |
08 | </ category ></ action ></ intent > |
10 | < service android:name = ".MusicService" android:enabled = "true" > |
13 | < uses android:minsdkversion = "8" -sdk = "" > |
4、res/layout/mail.xml的内容如下:
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
03 | < textview android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textsize = "20sp" android:text = "SharedPreferences的使用" android:id = "@+id/TextView01" > |
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" > |
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" > |
5、MainHelloSharedPreferences.java的内容如下:
01 | package android.basic.lesson19; |
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; |
15 | public class MainHelloSharedPreferences extends Activity { |
16 | /** Called when the activity is first created. */ |
18 | public void onCreate(Bundle savedInstanceState) { |
19 | super .onCreate(savedInstanceState); |
20 | setContentView(R.layout.main); |
23 | Button b1 = (Button) findViewById(R.id.Button01); |
24 | Button b2 = (Button) findViewById(R.id.Button02); |
27 | final ServiceConnection conn = new ServiceConnection() { |
30 | public void onServiceConnected(ComponentName name, IBinder service) { |
34 | public void onServiceDisconnected(ComponentName name) { |
39 | OnClickListener ocl = new OnClickListener() { |
41 | public void onClick(View v) { |
42 | Intent intent = new Intent(MainHelloSharedPreferences. this , |
43 | android.basic.lesson19.MusicService. class ); |
46 | Toast.makeText(getApplicationContext(), "Button01 onClick" , Toast.LENGTH_LONG).show(); |
48 | bindService(intent,conn,Context.BIND_AUTO_CREATE); |
51 | Toast.makeText(getApplicationContext(), "Button02 onClick" , Toast.LENGTH_LONG).show(); |
60 | b1.setOnClickListener(ocl); |
61 | b2.setOnClickListener(ocl); |
6、运行程序,查看运行情况:
![image image](http://android.yaohuiji.com/wp-content/uploads/2010/08/image_thumb7.png)
![image image](http://android.yaohuiji.com/wp-content/uploads/2010/08/image_thumb8.png)
查看 File Explorer,在/data/data/android.basic.lesson19/shared_prefs/目录下有一个MusicCurrentPosition.xml文件,点击右上角的按钮 pull a file from the device,可以把这个xml文拷贝出来
![MC~OMM~8XOFGC$YYMS$S$KL MC~OMM~8XOFGC$YYMS$S$KL](http://android.yaohuiji.com/wp-content/uploads/2010/08/MCOMM8XOFGCYYMSSKL_thumb.jpg)
7、查看MusicCurrentPosition.xml的内容,可以看到音乐播放进度的数据存贮在这个xml中
1 | <?xml version= '1.0' encoding= 'utf-8' standalone= 'yes' ?> |
3 | < int name= "CurrentPosition" value= "15177" > |
兴趣的同学可以尝试一下,在Activity中增加一个按钮,点击以后把SharedPreference中的播放进度数据取出来,显示在另一个文本框Textview02里,我在这里把最后的运行结果图放这里,代码你们可以自己练习着敲出来,从中体会Share的意思,是不是在同一个APK中不同的组件之间都可以去访问这个共享的持久化数据?从这一点上说是不是有点像是Cookie?
![image image](http://android.yaohuiji.com/wp-content/uploads/2010/08/image_thumb9.png)
转载
http://android.yaohuiji.com/archives/672