SharedPreferences-共享参数实现理解

一、概述

SharedPreferences类似于Windows程序中常用的ini文件,以Key-Value的形式来保存应用程序的属性设置信息(区分数据类型)。比如,可以用来保存用户上一次的登录信息;可以保存媒体播放程序的音量设置以及上次播放位置等。

二、数据以XML文件的方式,保存在data/data/pacakge name/shared_prefs/目录下,注意:只有保存过一次数据,shared_prefs目录和下的配置文件才存在。

三、实现方法:

1、保存数据:

private SharedPreferences ps;

ps = this.getSharedPreferences("test",Activity.MODE_PRIVATE);

Editor editor =settings.edit();
editor.putInt("key",8);
editor.commit();

2、读取数据

int key = ps.getInt("key",0);//从test.xml配置文件中读取KEY的值,没有则赋值为0;

四、getPreferences和getSharedPreferences的区别

1、getPreferences只能由Activity调用,只在调用它的Activity范围内有效。
2、getSharedPreferences是由Context调用,在包范围内有效。

3、另外:因为getPreferences是activity有效,SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);所以这个函数没有指明配置文件名,其配置文件名为类名。

五、操作模式说明:

Context.MODE_PRIVATE:新内容覆盖原内容

Context.MODE_APPEND:新内容追加到原内容后
Context.MODE_WORLD_READABLE:允许其他应用程序读取
Context.MODE_WORLD_WRITEABLE:允许其他应用程序写入,会覆盖原数据。

六、程序间共享SharedPreferences

A程序提供共享数据:A程序包名为com.leno.ex_data

private SharedPreferences sp;

sp = getSharedPreferences("ex_data", MODE_WORLD_READABLE);//操作模式为允许其他程序读取
Editor editor =sp.edit();
editor.putString("login",et_login.getText().toString());

editor.commit();

B程序读取A程序的配置数据:

Context other_apps_context = null;
try 
{
  //获取共享数据A程序的包上下文环境
  other_apps_context = createPackageContext("com.leno.ex_data", 0);
} 
catch (NameNotFoundException e)
{
}
//从A程序的上下文环境获取共享参数对象SharedPreferences
SharedPreferences other_app_sp = other_apps_context.getSharedPreferences(
				"ex_data", Context.MODE_PRIVATE);
//读取数据
String str = other_app_sp.getString("login","");


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值