Document for Commit ()
Official documents are as follows:
Commit your preferences changes back from this Editor to the Sharedpreferences object it is editing. This atomically performs the requested modifications, replacing whatever are currently in the sharedpreferences.
Note that when both editors is modifying preferences at the same time and the last one to call commit wins.
If you don ' t care about the return value and your ' re using this from your application ' s main thread, consider using apply () instead.
Document for Apply ()
Official documents are as follows:
Commit your preferences changes back from this Editor to the Sharedpreferences object it is editing. This atomically performs the requested modifications, replacing whatever are currently in the sharedpreferences.
Note that when both editors is modifying preferences at the same time, the last one to call apply wins.
Unlike commit (), which writes its preferences out to persistent storage synchronously, apply () commits it changes to the In-memory Sharedpreferences immediately but starts a asynchronous commit to disk and you won ' t being notified of any failure S. If another editor on this sharedpreferences does a regular commit () when a apply () is still outstanding, the commit () would block until all Async commits is completed as well as the commit itself.
As Sharedpreferences instances is singletons within a process, it's safe to replace any instance of commit () with apply () If you were already ignoring the return value.
You don ' t need to worry about Android component lifecycles and their interaction with apply () writing to disk. The framework makes sure in-flight disk writes from apply () complete before switching states.
Explanatory notes
It is important to note that the commit()
method is Added in API level 1
, that is, sdk1
already exists.
apply()
The method is Added in API level 9
.
commit()
There is a return value, a successful return true
, and a failed return false
. commit()
The method is to synchronously commit to the hardware disk, so that when multiple concurrent commit commits, they will wait for the commit to be processed after being saved to disk, thereby reducing the efficiency.
apply()
No return value. apply()
is to commit the modified data to memory and then asynchronously commit it to the hardware disk.
Why is it recommended to use apply () instead of commit ()?
A: because the Android designer found that the developer is not interested in the return value of the commit and that using commit is less efficient than apply when the data is being processed concurrently, apply is recommended.
The difference between the Apply () and commit () methods of Sharedpreferences.editor