本文介绍了在多进程模式下使用 SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个用于多进程模式的 SharedPreferences 实例.

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
}

现在我在具有单独进程的服务上以及在我的主应用程序进程中以静态方式使用此类.
一切都很顺利,但有时 SharedPreferences 实例上的所有存储数据都被删除了!
我该如何解决这个问题?

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.

推荐答案

目前没有办法在多个进程上安全地访问 SharedPreferences,如其 文档.

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

注意:该类不支持跨多个进程使用.

在使用 MODE_MULTI_PROCESS 进行大量测试后,我有三个试验要分享:

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

1- 在每个进程中初始化SharedPreferences一次并多次使用它.

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

问题:这些值没有按预期反映在每个流程中.所以每个进程都有自己的 SharedPreferences 值.

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

2- 在每个 put 或 get 中初始化 SharedPreferences.

2- Initialize the SharedPreferences in each put or get.

这确实有效,并且该值现在可以在进程之间互换.

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

问题:有时在主动访问 sharedpref 后,共享首选项文件及其所有内容都会被删除,如本 issue,我在日志中收到了这个警告:

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- 使用同步来锁定在SharedPreferences中放置和获取值的方法.

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

这是完全错误的;同步不能跨进程工作.SharedPreferences 实际上在其实现中使用了同步,但这只能确保线程安全,而不是进程安全.这在此处有很好的描述.

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.

这篇关于在多进程模式下使用 SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 21:39