SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据。
使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下
/** * 对SharePreference的封装 * * @author Kevin * */ public class PrefUtils { public static void putBoolean(String key, boolean value, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); sp.edit().putBoolean(key, value).commit(); } public static boolean getBoolean(String key, boolean defValue, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); return sp.getBoolean(key, defValue); } public static void putString(String key, String value, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); sp.edit().putString(key, value).commit(); } public static String getString(String key, String defValue, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); return sp.getString(key, defValue); } public static void putInt(String key, int value, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); sp.edit().putInt(key, value).commit(); } public static int getInt(String key, int defValue, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); return sp.getInt(key, defValue); } public static void remove(String key, Context ctx) { SharedPreferences sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE); sp.edit().remove(key).commit(); } }
PrefUtils.putBoolean("is_guide_show", true, this);
// 判断是否需要跳到新手引导
boolean isGuideShow = PrefUtils.getBoolean("is_guide_show",
false, getApplicationContext());