Android随笔:跨应用程序访问Preferences

  我们可以在一个应用程序中创建并编辑一个 Preferences,然后在另外一个应用程序中读取它。当然有个前提是该 Preferences的权限至少是 Context.MODE_WORLD_READABLE

比如在包名为 com.teleca应用程序A中有一个名叫com.teleca_prefer的Preferences:

java代码:


final static String preferName="com.teleca_prefer";

final static String KEY_TIP="tip";

prefsWorldRead = getSharedPreferences(preferName, Context.MODE_WORLD_READABLE);

Editor prefsWorldReadEditor = prefsWorldRead.edit();

prefsWorldReadEditor.putString(KEY_TIP, "Are you fine?");

prefsWorldReadEditor.commit();


我们可以在包名为com.teleca.robin应用程序B中这样读取它:

java代码:


private SharedPreferences prefsWorldRead;

final static String preferName="com.teleca_prefer";

final static String KEY_TIP="tip";

if(prefsWorldRead ==null) {

Context otherContext=null;

try {

otherContext =createPackageContext("com.teleca", Context.CONTEXT_IGNORE_SECURITY );

} catch (NameNotFoundException e)  {

e.printStackTrace();

}

prefsWorldRead = otherContext.getSharedPreferences(preferName, Context.MODE_WORLD_READABLE);

}

String tip=prefsWorldRead.getString(KEY_TIP, "null2");


createPackageContext为Context的方法,"com.teleca"为A应用程序的包名,"com.teleca_prefer"为你要读取的A应用程序的Preferences名字。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值