两个application 互相访问数据 (非shareUserId)

本文探讨了在Android中不同应用程序间通过SharedPreferences进行数据共享的方法。详细分析了不同模式下的行为差异,特别是MODE_MULTI_PROCESS的作用及其实现原理,并给出了跨应用写入SharedPreferences时遇到问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A

sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

A设置模式为READABLE AND WRITEABLE,这样其它的app才可以访问这个sharedPreferences

B

sharedPreferences = context.getSharedPreferences(pname, Context.MODE_MULTI_PROCESS);

B的模式必须设置为MODE_MULTI_PROCESS,如果设置为READABLE AND WRITEABLE的话只能读取第一次的值,以后当B修改了value,B是拿不到更新后的值的

下面是MODE_MULTI_PROCESS的说明

SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.
This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targetting such releases. For applications targetting SDK versions greater than Android 2.3, this flag must be explicitly set if desired.

note:

即使A设置了可读和可写的权限,B只能读取,不能修改,为什么呢?


使用createPackageContext() 向其他程序的SharedPreferences写入数据 时,即使该SharedPreferences是全局可写的,即-rw--rw-rw-,也会出现问题,操作失败。问题在于在向SharedPreferences写入数据,在该SharedPreferences所在的包路径下会产生一个临时存储的以.bak结尾的缓存文件,写入操作时,如果该包的权限没有做过必要的修改,默认是不让其他程序操作的,同样就不能在该包内创建临时文件,所以进而导致写入失败失败。

解决方法:如下,这样shared_prefs包的权限也就变为可读可写可执行的了,自然可以在该包内创建临时文件。

File dir = new File("/data/data/" + getPackageName() + "/shared_prefs/");
if (!dir.exists()){
dir.mkdirs();
}
dir.setReadable(true, false);
dir.setWritable(true, false);
dir.setExecutable(true, false);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值