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);