使用多进程模式共享preferences进程、模式、preferences

2023-09-05 03:33:05 作者:拉着沵的手ざ不离不弃

我定义的共享preferences 在多进程模式使用的一个实例。

I've defined an instance of SharedPreferences that used on multi-process mode.

public class Prefs {

    private static SharedPreferences prefs;
    private static SharedPreferences.Editor editor;

    private static void init(Context context) {

        prefs = context.getSharedPreferences("alaki",
                Context.MODE_MULTI_PROCESS);
        editor = prefs.edit();
    }

// static methods to set and get preferences
}

现在我使用的是带有独立的进程,并在静态的方式我的主要应用程序服务这一类。 一切都很顺利,但有时在共享preferences实例存储的所有数据删除! 我该如何解决这个问题呢?

Now I'm using this class on a service with separate process and also in my main application process in static way. Everything is going well, but sometimes all stored data on SharedPreferences instance removed! How can I solve this problem?

编辑: 最后,我已经解决了利用IPC我的问题。

Finally I've solved my problem using by IPC.

推荐答案

目前在描述目前还没有办法安全地访问共享preferences 的多个进程,其文档。

There is currently no way of safely accessing SharedPreferences on multiple processes, as described in its documentation.

注:目前这一类不支持跨多个应用   流程。这将在以后添加。

Note: currently this class does not support use across multiple processes. This will be added later.

测试了很多与 MODE_MULTI_PROCESS 之后,我有三个试验分享到:

After testing a lot with MODE_MULTI_PROCESS, I've three trials to share:

1 初始化共享preferences 曾经在每道工序并多次使用。

1- Initialize the SharedPreferences once in each process and use it multiple times.

的问题:的值未如预期反映的每一个过程。因此,每个进程都有自己的共享preferences的价值。

The problem: The values are not reflected in each process as expected. So each process has its own value of the SharedPreferences.

2 - 初始化每个共享preferences 放置或获得。

2- Initialize the SharedPreferences in each put or get.

这实际工作和价值,现在是可以互换的进程之间。

This actually works and the value now is interchangeable between processes.

的问题:有时在积极地访问共享preF,共享preferences文件删除了其所有的内容,如在此的 问题 ,我得到这样的警告日志中:

The problem: sometimes after aggressively accessing the sharedpref, the shared preferences file got deleted with all its content, as described in this issue, and I get this warning in the log:

W/FileUtils﹕ Failed to chmod(/data/data/com.hegazy.multiprocesssharedpref/shared_prefs/myprefs.xml): android.system.ErrnoException: chmod failed: ENOENT (No such file or directory)

您可以找到为什么发生这种情况的问题。

You can find why this happens in the issue.

3 使用同步锁定该放的方法,并在共享preferences设定值

3- Use synchronization to lock the methods that put and set values in the SharedPreferences.

这是完全错误的;同步不会在原有的工作流程。该共享preferences 实际使用同步在实施,但只保证线程安全,不处理的安全性。这是这里描述得非常好。

This is completely wrong; synchronization doesn't work across processes. The SharedPreferences is actually using synchronization in its implementation, but that only ensures thread safety, not process safety. This is described very well here.