提交与应用

editor.apply() 方法是异步,而 editor.commit()同步

显然,你应该叫 apply()commit()

Version >= 2.3

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() 在 2.3(API 9)中添加,它提交时不返回表示成功或失败的布尔值。

如果保存起作用,则 commit() 返回 true,否则返回 false。

apply() 被添加,因为 Android 开发团队注意到几乎没有人注意到返回值,因此应用更快,因为它是异步的。

commit() 同步地将其首选项写入持久存储器不同,apply() 会立即将其更改提交到内存中的 SharedPreferences,但会启动异步提交到磁盘,并且不会通知你任何故障。如果此 SharedPreferences 上的另一个编辑器执行常规 commit()apply() 仍然未完成,则 commit() 将阻塞,直到完成所有异步提交(应用)以及可能正在等待的任何其他同步提交。