自动分析类型,保存数据
/** * 缓存管理器 */ public class CacheManager { private static SharedPreferences sp = null; private static Context context; /** * 读取缓存的信息 */ public static void initCache(Context context) { CacheManager.context = context; sp = context.getSharedPreferences(Constant.SETTINGS_KEY, Context.MODE_PRIVATE); } /** * 向sharepreferences存入键值对 */ public static boolean addCache(String[] keys, Object[] values) { if (keys.length != values.length) { return false; } SharedPreferences sp = context.getSharedPreferences(Constant.SETTINGS_KEY, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); for (int i = 0; i < keys.length; i++) { if (values[i] instanceof String) { editor.putString(keys[i], (String) values[i]); } else if (values[i] instanceof Boolean) { editor.putBoolean(keys[i], (Boolean) values[i]); } else if (values[i] instanceof Integer) { editor.putInt(keys[i], (Integer) values[i]); } else if (values[i] instanceof Long) { editor.putLong(keys[i], (Long) values[i]); } else if (values[i] instanceof Float) { editor.putFloat(keys[i], (Float) values[i]); } } editor.commit(); return true; } public static String getString(String key, String defaultValue) { if (sp == null) { return defaultValue; } return sp.getString(key, defaultValue); } public static boolean getBoolean(String key, boolean defaultValue) { if (sp == null) { return defaultValue; } return sp.getBoolean(key, defaultValue); } public static int getInt(String key, int defaultValue) { if (sp == null) { return defaultValue; } return sp.getInt(key, defaultValue); } public static long getLong(String key) { if (sp == null) { return 0; } return sp.getLong(key, 0L); } public static boolean remove(String key) { if (sp == null) { return false; } SharedPreferences.Editor editor = sp.edit(); editor.remove(key); editor.commit(); return true; } }