我有两个项目使用相同的共享首选项. Project1和Project2.它们是独立但相关的应用程序.他们使用相同的密钥进行签名,并使用sharedUserId来共享信息.
Project1打开Project2.
Project2检索SharedPreferences文件并通过以下方式写入:
Context prefsContext = c.createPackageContext(packageNameOfProject1,Context.CONTEXT_IGNORE_SECURITY); SharedPreferences prefs = prefsContext.getSharedPreferences(fileName,Context.MODE_PRIVATE); SharedPreferences.editor editor = prefs.edit(); editor.putBool("bool1",value1); editor.putBool("bool2",value2); ... editor.putBool("boolN",valueN); editor.apply();
一旦完成,我通过调用finish()返回到Project1.
Project1然后读取数据如下:
SharedPreferences prefs = getSharedPreferences(getPreferencesFileName(),Context.MODE_PRIVATE); Boolean value1 = prefs.getBoolean(fileName,false); Boolean value2 = prefs.getBoolean(fileName,false); ... Boolean valueN = prefs.getBoolean(fileName,false); Map<String,?> mappings = prefs.getAll(); Set<String> keys = mappings.keySet(); for(String key : keys) { log.d(TAG,"_____"); log.d(TAG,"Key = " + key); log.d(TAG,"Value = " + mappings.get(key)); }
问题是在Project1中没有更新值.我可以告诉基于日志的最后文件甚至不生成映射.但是,我可以验证xml是否正在更新.如果我强制停止应用程序,然后重新启动它,所有的映射都在Project1中.所有的值都是正确的.但是,当用户离开Project2时,我需要更新.我觉得有一些我在这里失踪但不能发现.
我能够找到的唯一的事情是:
SharedPreferences.Editor not being updated after initial commit
SharedPreferences value is not updated
这些没有帮助,因为我已经这样做了.
我在两个清单中都设置了WRITE_EXTERNAL_STORAGE. fileName是一样的(否则当我重新输入应用程序时,我将无法读取该文件).
编辑:
我应该注意到,我试图做editor.commit()而不是editor.apply(),因为我以为我正在面对一个竞争条件.问题依然存在.我在想,由于某些原因,即使我每次都在懒惰加载它,而是使用Project1中的SharedPreference的旧引用而不是新的.
EDIT2:
好的,进一步测试看看什么ID.我决定尝试相反的方向.
在Project1中我做:
Float testFloat (float) Math.random(); Log.d("TEST_FLOAT","Project1: TEST_FLOAT = " + testFloat); prefs.edit().putFloat("TEST_FLOAT",testFloat).commit();
在Project2中我做:
Log.d("TEST_FLOAT","Project2: TEST_FLOAT = " + prefs.getFloat("TEST_FLOAT",0.0f));
然后我在两者之间来回移动:Project1-> Project2-> Project1-> Project2-> Project1-> Project2,这里是logcat结果:
Project1: TEST_FLOAT = 0.30341884 Project2: TEST_FLOAT = 0.30341884 Project1: TEST_FLOAT = 0.89398974 Project2: TEST_FLOAT = 0.30341884 Project1: TEST_FLOAT = 0.81929415 Project2: TEST_FLOAT = 0.30341884
换句话说,它正在读写同一个文件.但是,当它在项目中首次打开时,它保留了它所具有的映射.即使我关闭了项目,映射仍然保留,直到应用程序被强制停止.
解决方法
更换
getSharedPreferences(fileName,Context.MODE_PRIVATE);
同
getSharedPreferences(fileName,Context.MODE_MULTI_PROCESS);
根据文件:
Context.MODE_MULTI_PROCESS
SharedPreferences 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 targeting
such releases. For applications targeting SDK versions greater than
Android 2.3(Gingerbread),this flag must be explicitly set if desired.
我知道这里有一个简单的监督.