提交與應用
該 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()
將阻塞,直到完成所有非同步提交(應用)以及可能正在等待的任何其他同步提交。