SharedPreferences是Android平台上一个轻量级的存储类,
主要是保存一些常用的配置比如窗口状态,一般在Activity中重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成。
它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存。
SharedPreferences使用实例如下:
public class PreferencesHelper { private Context context = null;//上下文 private String name = "";//名称 private SharedPreferences preferences = null; public PreferencesHelper(Context ctx, String name){ context = ctx; this.name = name; preferences = getPerferences(); } private SharedPreferences getPerferences(){ SharedPreferences per = context.getSharedPreferences(name, Context.MODE_PRIVATE); return per; } public boolean setString(String key, String val){ return preferences.edit().putString(key, val).commit(); } public String getString(String key, String defaultValue){ return preferences.getString(key, defaultValue); } public boolean setBoolean(String key, boolean val){ return preferences.edit().putBoolean(key, val).commit(); } public boolean getBoolean(String key, boolean defaultValue){ return preferences.getBoolean(key, defaultValue); } public boolean setFloat(String key, float val){ return preferences.edit().putFloat(key, val).commit(); } public float getFloat(String key, float defaultValue){ return preferences.getFloat(key, defaultValue); } public boolean setInt(String key, int val){ return preferences.edit().putInt(key, val).commit(); } public int getInt(String key, int defaultValue){ return preferences.getInt(key, defaultValue); } public boolean setLong(String key, long val){ return preferences.edit().putLong(key, val).commit(); } public long getLong(String key, long defaultValue){ return preferences.getLong(key, defaultValue); } public Map<String, ?> getAll(){ return preferences.getAll(); } public void clear(){ Editor editor = preferences.edit(); Map<String, ?> map = preferences.getAll(); for (Map.Entry<String, ?> e : map.entrySet()) { editor.remove(e.getKey()); editor.commit(); } } }