【问题标题】:Reading Old Values From SharedPreferences File X-Application从 SharedPreferences 文件中读取旧值 X-Application
【发布时间】:2014-04-28 15:29:30
【问题描述】:

我正在创建并写入 SharedPreferences 文件以存储来自一个应用程序的配置信息,如下所示:

public void setCustomAsync (. . . final Context context . . .) {
    if (prefs == null || editor == null) {
        prefs  = context.getSharedPreferences("prefs", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
        editor = prefs.edit();
    }
    editor.putString("Custom", info); // This may be changing a previously set value
    editor.apply();

    // Creating backups of the preferences file
    execCommand(copyToBackup);
    execCommand(mainFixPerm);
    execCommand(bakFixPerm);
    activity.finish();
}

public void execCommand (String[] arg0) {
    try {
    final Process pr = Runtime.getRuntime().exec(arg0);
    final int retval = pr.waitFor();
    if (retval != 0) { Log.d("ERROR:", String.valueOf(retval)); }
    } catch (Exception e) {}
}

我正在从另一个应用程序中读取该信息:

private static String getCustom (final Context appContext) throws NameNotFoundException {
    context = appContext.createPackageContext("com.example.settings", 0);
    prefs   = context.getSharedPreferences("prefs", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
    return prefs.getString("Custom", EMPTY);
}

我的问题不是我无法获取文件,而是第二个应用程序读取时值不是最新的

调试第一个应用程序后,我可以看到将新配置保存到文件中工作正常,但只有当第二个应用程序重新启动时,它才会显示更新的配置。否则它会继续读取旧值。

现在我在阅读有关 SharedPreferences here 时看到

“从各种 get 方法返回的对象必须被应用程序视为不可变的。”

但是每次我在第二个应用程序中从文件中读取值时,我都会重述首选项,所以我将它作为新的东西拉进来对吗?我不确定这是否是问题以及如何解决这个问题。

谢谢!

注意:我发布的代码是从我的实际应用程序中转述的,只保留与问题相关的部分。

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    我需要在其他两个要求之上添加 Context.MODE_MULTI_PROCESS。仅在较新的 API 中可用。

    【讨论】:

      猜你喜欢
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多