SharedPreferences作为Android的五大存储结构之一,在保存简单数据类型上因效率高而被广泛应用.可为应用程序记录退出前的数据.直接上实例:
package com.example.global;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class Setting {
public static final String PREFERENCE_NAME = "AlarmSetting";
public static final String FLAG_HOUR = "hour";
public static final String FLAG_MINUTE = "minute";
public static final String FLAG_ENABLE = "enable";
public static int hour;
public static int minute;
public static boolean enable;
public static void getSetting(Context context){
SharedPreferences sp = context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
sp.getInt(FLAG_HOUR, 0);
sp.getInt(FLAG_MINUTE, 0);
sp.getBoolean(FLAG_ENABLE, false);
}
public static void saveSetting(Context context){
SharedPreferences sp = context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putInt(FLAG_HOUR, hour);
edit.putInt(FLAG_MINUTE, minute);
edit.putBoolean(FLAG_ENABLE, enable);
edit.apply();
}
}
在提交数据时可使用commit()和apply()两个方法,其区别在于:
1. apply没有返回值而commit返回boolean表明修改是否提交成功。
3. apply方法不会提示任何失败的提示。
由于在一个进程中,sharedPreference是单实例,一般不会出现并发冲突,如果对提交的结果不关心的话,建议使用apply,当然需要确保提交成功且有后续操作的话,还是需要用commit的。