与其他应用共享共享首选项会提供旧/缓存值

时间:2018-06-07 09:22:49

标签: android android-sharedpreferences

我有两个应用程序,比如A和B.应用程序A有一个共享的pref,它被创建为全局可读,以便应用程序B可以访问它。 当我第一次尝试从应用B访问App A的共享pref值时,它会给出正确的结果。但是当我更改应用A的共享pref值然后打开应用B以检查更新的共享pref它给出相同的旧值时,问题就出现了。令人惊讶的是,当我从设置强制关闭应用B时 - >应用程序并重新打开应用程序B它会提供应用程序A的共享首选项的正确更新值。

当应用程序是WORLD_READABLE时,访问共享pref是什么问题。

当我访问应用A 的共享首部时,以下是应用B 的源代码。

private boolean isDAEnabled() throws SecurityException {
    Context context = null;
    try {
        context = createPackageContext(APP_A_PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (context == null) {
        throw new SecurityException("can not read shared pref of old DAE");
    }

    SharedPreferences oldDaPrefs = context.getSharedPreferences
            (A_SHAREDPREF_FILE_NAME, Context.MODE_WORLD_READABLE);

    int what = oldDaPrefs.getInt(A_PREF_ENGINE_STATE, 4);
    Log.d(TAG, "What is value "+ what);
    return  what == ENABLE_ENGINE; // ENABLE_ENGINE IS == 0

}

以下是我要更改 App A

的共享首选项的代码
private void setEnginePreference(boolean engineStatus) {
    mPreferenceEditor = mPreference.edit();
    if(engineStatus){
        mPreferenceEditor.putInt(Constants.PREF_ENGINE_STATE, ENABLE_ENGINE);
    } else {
        mPreferenceEditor.putInt(Constants.PREF_ENGINE_STATE, DISABLE_ENGINE);
    }
    mPreferenceEditor.commit();
}

2 个答案:

答案 0 :(得分:0)

改变这个:

private void setEnginePreference(boolean engineStatus) {
    mPreferenceEditor = mPreference.edit();
    if(engineStatus){
        mPreferenceEditor.putInt(Constants.PREF_ENGINE_STATE, ENABLE_ENGINE);
    } else {
        mPreferenceEditor.putInt(Constants.PREF_ENGINE_STATE, DISABLE_ENGINE);
    }
    mPreferenceEditor.commit();
}

致:

private void setEnginePreference(boolean engineStatus) {
    mPreferenceEditor = mPreference.edit();
    if(engineStatus){
        mPreferenceEditor.putInt(Constants.PREF_ENGINE_STATE, ENABLE_ENGINE);
    } else {
        mPreferenceEditor.putInt(Constants.PREF_ENGINE_STATE, DISABLE_ENGINE);
    }
    mPreferenceEditor.apply();
}

答案 1 :(得分:0)

回答我自己的问题,因为我已经找到了解决方案。

我在blog中发现我可以在访问不同应用程序的共享首选项时使用MODE_MULTI_PROCESS(例如 app A )。但是,从API Level 23(OS 6.0版)开始,不推荐使用Context.MODE_MULTI_PROCESS。但我的要求只是支持API级别23,所以这对我有好处。

这是我必须做出的改变

private boolean isDAEnabled() throws SecurityException {
Context context = null;
try {
    context = createPackageContext(APP_A_PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY);
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}
if (context == null) {
    throw new SecurityException("can not read shared pref of old DAE");
}

SharedPreferences oldDaPrefs = context.getSharedPreferences
        (A_SHAREDPREF_FILE_NAME, Context.MODE_MULTI_PROCESS);

int what = oldDaPrefs.getInt(A_PREF_ENGINE_STATE, 4);
Log.d(TAG, "What is value "+ what);
return  what == ENABLE_ENGINE; // ENABLE_ENGINE IS == 0}

我希望它能帮助别人。

相关问题