There is currently no way of safely accessing SharedPreferences
on multiple processes, as described in its documentation.
Note: This class does not support use across multiple processes.
After testing a lot with MODE_MULTI_PROCESS
, I've three trials to share:
1- Initialize the SharedPreferences
once in each process and use it multiple times.
The problem: The values are not reflected in each process as expected. So each process has its own value of the SharedPreferences.
2- Initialize the SharedPreferences
in each put or get.
This actually works and the value now is interchangeable between processes.
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- Use synchronization to lock the methods that put and get values in the 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…