这个问题已经有了答案,但如果其他人来并正在寻找代码示例,我将这个实用程序类放在一起用于与 SharedPreferences 进行交互。
调用 commit() 将使用 apply() 方法(如果可用),否则在旧设备上将默认返回 commit() :
public class PreferencesUtil {
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
private Context mAppContext;
private static PreferencesUtil sInstance;
private boolean mUseApply;
//Set to private
private PreferencesUtil(Context context) {
mAppContext = context.getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(mAppContext);
prefsEditor = prefs.edit();
//Indicator whether or not the apply() method is available in the current API Version
mUseApply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
public static PreferencesUtil getInstance(Context context) {
if (sInstance == null) {
sInstance = new PreferencesUtil(context);
}
return sInstance;
}
public boolean getBoolean(String key, boolean defValue) {
return prefs.getBoolean(key, defValue);
}
public int getInt(String key, int defValue) {
return prefs.getInt(key, defValue);
}
public String getString(String key, String defValue) {
return prefs.getString(key, defValue);
}
public String getString(String key) {
return prefs.getString(key, "");
}
public void putBoolean(String key, boolean value) {
prefsEditor.putBoolean(key, value);
}
public void putInt(String key, int value) {
prefsEditor.putInt(key, value);
}
public void putString(String key, String value) {
prefsEditor.putString(key, value);
}
/**
* Sincle API Level 9, apply() has been provided for asynchronous operations.
* If not available, fallback to the synchronous commit()
*/
public void commit() {
if (mUseApply)
//Since API Level 9, apply() is provided for asynchronous operations
prefsEditor.apply();
else
//Fallback to syncrhonous if not available
prefsEditor.commit();
}
}