The editor.apply()
method is asynchronous, while editor.commit()
is synchronous.
Obviously, you should call either apply()
or commit()
.
SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_CONST, true);
// This will asynchronously save the shared preferences without holding the current thread.
editor.apply();
SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREF_CONST, true);
// This will synchronously save the shared preferences while holding the current thread until done and returning a success flag.
boolean result = editor.commit();
apply()
was added in 2.3 (API 9), it commits without returning a boolean indicating success or failure.
commit()
returns true if the save works, false otherwise.
apply()
was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.
Unlike commit()
, which writes its preferences out to persistent storage synchronously, apply()
commits its changes to the in-memory SharedPreferences
immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences
does a regular commit()
while a apply()
is still outstanding, the commit()
will block until all async commits(apply) are completed as well as any other sync commits that may be pending.