外部更改时重新加载SharedPreferences(不杀死应用程序)

时间:2017-03-19 21:07:47

标签: android sharedpreferences

我正在备份Shared_prefs并且它成功恢复,但是在重新加载活动时没有更新值(finish(); statActivity(...);)。
它需要被杀死然后它会加载价值.... 这是我的代码:

this

每次,在创建或刷新活动时,我都将此功能称为

<table>
  <tr>
    <td class="thing"> 1 </td>
    <td class="thing"> 2 </td>
  </tr>  
</table>

但是价值保持不变,直到app如上所述被杀。
我的问题是:一旦xml​​资源文件(在data / data /.../ shared_prefs中)被更改或删除然后手动添加,如何重新加载首选项?

1 个答案:

答案 0 :(得分:0)

根据Android文档,您需要使用MODE_MULTI_PROCESS模式来通知磁盘更改为共享首选项,无论如何,此方法现在已被弃用,但这是实现此过程的一种可能方法。

public static boolean reloadSharedPreference(Context context, String name) {
    return context.getSharedPreferences(name, Context.MODE_MULTI_PROCESS)
            .edit()
            .putBoolean("RELOAD", true)
            .commit();
}

请参阅Android文档:

/**
 * 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.
 *
 * <p>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 <em>greater than</em> Android 2.3, this flag must be
 * explicitly set if desired.
 *
 * @see #getSharedPreferences
 *
 * @deprecated MODE_MULTI_PROCESS does not work reliably in
 * some versions of Android, and furthermore does not provide any
 * mechanism for reconciling concurrent modifications across
 * processes.  Applications should not attempt to use it.  Instead,
 * they should use an explicit cross-process data management
 * approach such as {@link android.content.ContentProvider ContentProvider}.
 */
@Deprecated
public static final int MODE_MULTI_PROCESS = 0x0004;