First, let's talk about the definition of SharedPreferences:
In the frameworks \ base \ core \ java \ android \ content \ SharedPreferences. java file, the Interface that defines SharedPreferences. Has its second article to explain:
Section 1:
Interface for accessing and modifying preference data returned by {@ linkContext # getSharedPreferences}. This shows that Preferences actually implement data access and modification.
Section 2
For any special set of preferences, there is a single instance of this class that all clients share. this indicates a specific preferences, which is actually shared by multiple customers.
Based on the above two English paragraphs, we can find out what SharedPreferences are and what they are. Next, I will undo the SharedPreferences secret step by step.
SharedPreferences. java just defines an interface of SharedPreferences. In fact, what actually implements it is here: SharedPreferencesImpl. java. Let's see what he is doing:
First, let's look at its constructor:
SharedPreferencesImpl(File file, int mode) { mFile = file; mBackupFile = makeBackupFile(file); mMode = mode; mLoaded = false; mMap = null; startLoadFromDisk(); }Here we focus on the function's
The first parameter is file. A file is passed. How is this file created?We will not talk about it, but we will discuss it later. Now we only focus on the implementation of SharedPreferencesImpl.
Let's look at another function:
public Editor edit() { // TODO: remove the need to call awaitLoadedLocked() when // requesting an editor. will require some work on the // Editor, but then we should be able to do: // // context.getSharedPreferences(..).edit().putString(..).apply() // // ... all without blocking. synchronized (this) { awaitLoadedLocked(); } return new EditorImpl(); }
When obtaining a SharedPreferences instance, you need to call this function to obtain the SharedPreferences operation. The returned value is an Editor. Therefore, operations such as writing data and reading data to a SharedPreferences are all about the Editor of this SharedPreferences, so let's focus on what the Editor has done.
Let's take a look at the implementation class EditorImpl of this Editor, which is actually an internal Final class of SharedPreferencesImpl (some code is given below ):
public final class EditorImpl implements Editor { private final Map
mModified = Maps.newHashMap(); private boolean mClear = false; public Editor putString(String key, String value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putStringSet(String key, Set
values) { synchronized (this) { mModified.put(key, (values == null) ? null : new HashSet
(values)); return this; } } public Editor putInt(String key, int value) { synchronized (this) { mModified.put(key, value); return this; } }... ...
Here we are following
It defines the private variable mModified of a HashMap.Let's look at the putInt () z functions,
Writing data to SharedPreferences is actually adding data to the HashMap of mModified.You will say, No. Can data written into HashMap be permanently saved? Of course not. Don't panic. Let's take a look at a function of this internal class:
public void apply() { final MemoryCommitResult mcr = commitToMemory(); final Runnable awaitCommit = new Runnable() { public void run() { try { mcr.writtenToDiskLatch.await(); } catch (InterruptedException ignored) { } } }; QueuedWork.add(awaitCommit); Runnable postWriteRunnable = new Runnable() { public void run() { awaitCommit.run(); QueuedWork.remove(awaitCommit); } }; SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable); // Okay to notify the listeners before it's hit disk // because the listeners should always get the same // SharedPreferences instance back, which has the // changes reflected in memory. notifyListeners(mcr); }We can see a line of code: SharedPreferencesImpl. this. enqueueDiskWrite (mcr, postWriteRunnable). What does this function do?
private void enqueueDiskWrite(final MemoryCommitResult mcr, final Runnable postWriteRunnable) { final Runnable writeToDiskRunnable = new Runnable() { public void run() { synchronized (mWritingToDiskLock) { writeToFile(mcr); } synchronized (SharedPreferencesImpl.this) { mDiskWritesInFlight--; } if (postWriteRunnable != null) { postWriteRunnable.run(); } } }; final boolean isFromSyncCommit = (postWriteRunnable == null); // Typical #commit() path with fewer allocations, doing a write on // the current thread. if (isFromSyncCommit) { boolean wasEmpty = false; synchronized (SharedPreferencesImpl.this) { wasEmpty = mDiskWritesInFlight == 1; } if (wasEmpty) { writeToDiskRunnable.run(); return; } } QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable); }First, this function ANDROID provides a description for us to see: Enqueue an already-committed-to-memory result to be written to disk. it seems that the data is written into the DISK ????
Note that this function defines a Runnable variable: writeToDiskRunnable. The important code executed in it is writeToFile (mcr );I guess you can understand what he is doing here! Indeed, just like what you think, it is actually writing the data stored in a HashMap into a file. If you don't believe it, let's continue to look at writeToFile (mcr); what does this function do.
WriteToFile (mcr); this function contains such an important piece of code that you can fully understand after reading it,
FileOutputStream str = createFileOutputStream(mFile); if (str == null) { mcr.setDiskWriteResult(false); return; } XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str); FileUtils.sync(str); str.close(); ContextImpl.setFilePermissionsFromMode(mFile.getPath(), mMode, 0);Check the first line of code: FileOutputStream str = createFileOutputStream (mFile); Do you still remember the file that caught your attention? Is mFile used at last. OK,
The data is written in this file.
XmlUtils. writeMapXml (mcr. mapToWriteToDisk, str); Where does mcr. mapToWriteToDisk data come from? In fact, mapToWriteToDisk is the HashMap of the stored data we just mentioned. You can see the following code:
private MemoryCommitResult commitToMemory() { MemoryCommitResult mcr = new MemoryCommitResult(); synchronized (SharedPreferencesImpl.this) { // We optimistically don't make a deep copy until // a memory commit comes in when we're already // writing to disk. if (mDiskWritesInFlight > 0) { // We can't modify our mMap as a currently // in-flight write owns it. Clone it before // modifying it. // noinspection unchecked mMap = new HashMap
(mMap); } mcr.mapToWriteToDisk = mMap;
The following code is available in this function commitToMemory:
for (Map.Entry
e : mModified.entrySet()) { String k = e.getKey(); Object v = e.getValue(); if (v == this) { // magic value for a removal mutation if (!mMap.containsKey(k)) { continue; } mMap.remove(k); } else { boolean isSame = false; if (mMap.containsKey(k)) { Object existingValue = mMap.get(k); if (existingValue != null && existingValue.equals(v)) { continue; } } mMap.put(k, v); }
Now, mModified, which originally stores data temporarily, transfers the data to mapToWriteToDisk.
Now I understand.In fact, the principle of SharedPreferences is to first store the data in hashmap and then write it into a file.So what file is written into this file? What is the file name? What is the relationship with an APP? What is the relationship between the preferences mentioned above? "This indicates a specific preferences, which is actually shared by multiple customers? For details, see the following breakdown:
In general, we obtain a SharedPreferences using the following code:
SharedPreferences prefs = PreferenceManager. getdefasharsharedpreferences (this );
(1) here this is of course the Context of the current Activity or Service. We know that the Activity and Service are essentially the same, and they all inherit the Context.
(2) The getdefasharsharedpreferences (Context context) function is defined in the PreferenceManager CLASS as follows:
public static SharedPreferences getDefaultSharedPreferences(Context context) { return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode()); }After reading this function, you must be enlightened. getdefasharsharedpreferences is a static function, which is actually the SharedPreferences obtained through this context. First, let's take a look at the parameters passed by the getdefasharsharedpreferencesname (context) function:
private static String getDefaultSharedPreferencesName(Context context) { return context.getPackageName() + "_preferences"; }Originally, a string is passed, and the string is composed of PackageName + _ preferences of the current APP. What do you see now? We know that an APP can have a large number of activities and services, and their PackageName is the same. Do all the activities and services of an APP pass the same string to get a SharedPreferences?
Is it hard to say that all the activities and services of an APP share a SharedPreferences? Is that true? Let's continue:
So we finally followed the implementation of the getSharedPreferences function of context.
We know that Context. java only defines the interface in Context. The actual implementation of this interface is here ContextImpl. java, So we quickly found the definition of this function:
public SharedPreferences getSharedPreferences(String name, int mode) { SharedPreferencesImpl sp; synchronized (sSharedPrefs) { sp = sSharedPrefs.get(name); if (sp == null) { File prefsFile = getSharedPrefsFile(name); sp = new SharedPreferencesImpl(prefsFile, mode); sSharedPrefs.put(name, sp); return sp; } } if ((mode & Context.MODE_MULTI_PROCESS) != 0 || getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { // If somebody else (some other process) changed the prefs // file behind our back, we reload it. This has been the // historical (if undocumented) behavior. sp.startReloadIfChangedUnexpectedly(); } return sp; }The getSharedPreferences function is simple:
(1) first, get a SharedPreferencesImpl instance by passing in the name. SharedPreferencesImpl has already said above, and he is actually a SharedPreferences. This is obtained through sSharedPrefs. get (name); this code. You will be surprised to see the definition of sSharedPrefs:
private static final HashMap
sSharedPrefs = new HashMap
();
SSharedPrefs is a private and most important one: static and final HashMap. . The most important thing here is to understand static: this means that sSharedPrefs is shared by all Context instances. That is to say, in principle, all apps so currently have available SharedPreferences.
What if the SharedPreferences that need to be used does not exist in sSharedPrefs? Of course, you need to create a new SharedPreferences, and then add it to sSharedPrefs to see the above function: the implementation of getSharedPreferences will know:
if (sp == null) { File prefsFile = getSharedPrefsFile(name); sp = new SharedPreferencesImpl(prefsFile, mode); sSharedPrefs.put(name, sp); return sp; }(1) I posted the code for creating a new SharedPreferences. We can see that a File is created by name. Let's take a look at what files have been created:
public File getSharedPrefsFile(String name) { return makeFilename(getPreferencesDir(), name + ".xml"); }
Now we can see that a. xml file is created. The file name is actually the name. The name is actually composed of PackageName + _ preferences of the APP.
(2) After the XML file is created, sp = new SharedPreferencesImpl (prefsFile, mode); then a SharedPreferencesImpl instance is created. Let's review: When we first introduced the implementation of SharedPreferencesImpl, we talked about its constructor. One Parameter of this constructor is file, a file. Now we can see that this file is actually an XML file.
Therefore, for an APP's SharedPreferences "all clients share", it means that all clients share the SharedPreferences of an APP. Here, clients clearly refers to all the activities and services of the APP.