繁体   English   中英

Android SharedPreferences在多个进程之间不一致

[英]Android SharedPreferences not consistent between multiple processes

我在尝试使SharedPreferences工作时遇到麻烦。

这是代码:

/**
 * Sets the software in synchronizing status.
 * @param synchronizing Boolean
 */
public void setSynchronizing(boolean synchronizing) {
    if(D) Log.d(TAG, "Called: setSynchronizing("+synchronizing+")");
    SharedPreferences preferences = mContext.getSharedPreferences(SharedPrefsConstants.PREFERENCES, 0);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(SharedPrefsConstants.SYNCHRONIZING, synchronizing);
    boolean result = editor.commit();
    if(!result)
        Log.w(TAG, "Cannot store the preference.");
    if(!synchronizing)
        BroadcastUtils.stopSynchronizing(mContext);
}

/**
 * Returns whether the software is synchronizing.
 * @return True if synchronization is happening.
 */
public boolean isSynchronizing() {
    SharedPreferences preferences = mContext.getSharedPreferences(SharedPrefsConstants.PREFERENCES, 0);
    boolean synchronizing = preferences.getBoolean(SharedPrefsConstants.SYNCHRONIZING, false);
    if(D) Log.d(TAG, "Called: isSynchronizing Returning: "+synchronizing);
    return synchronizing;
}

这是logcat的输出,请注意,我在应用程序中使用了两个单独的进程,我将它们分别称为appapp:bg

**app** D/StorageManager﹕ Called: setSynchronizing(true)
**app** D/StorageManager﹕ Called: setSynchronizing(true)
**app** D/StorageManager﹕ Called: isSynchronizing Returning: true
**app** D/StorageManager﹕ Called: isSynchronizing Returning: true
**app:bg** D/StorageManager﹕ Called: setSynchronizing(false)
**app** D/StorageManager﹕ Called: isSynchronizing Returning: true

StorageManager是一个单例实例,但其中有两个实例,每个实例一个。

即使从后台线程调用setSynchronizing(false),物理首选项文件也已正确更改,但是在前台线程中它仍然为true。

您可以看到在setSynchronizing将变量设置为false之后,isSynchronizing方法返回true。 问题是: 为什么会这样? 这是我第一次在此软件中使用SharedPreferences,因此无法在其他任何地方进行设置。

当isSynchronizing仍返回TRUE时,这是手机中存储的首选项文件:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="synchronizing" value="false" />
</map>

我唯一能想到的是,SharedPreferences在内存中拥有某种缓存,如果您可以确认这一点,则可以通过某种方式强制更新SharedPreference?

我还必须说,在将变量设置为false以及从前台线程对isSynchronizing进行的任何其他后续调用之间,要花费大量的时间。

我找到了解决方案。

似乎SharedPreferences不是一个进程安全的类,如果在调用getSharedPreferences时设置一个标志,它可以与多个进程一起使用:

MODE_MULTI_PROCESS

这样就解决了问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM