public class SharedCache {
/**
* boolean 值放入缓存
*
* @param context
* @param key
* @param value
*/
public static void putBoolean(Context context, String key, boolean value) {
context.getSharedPreferences("MusicCache", Context.MODE_PRIVATE).edit()
.putBoolean(key, value).commit();
}
/**
* 从缓存中读取出boolean 值
*
* @param context
* @param key
* @return
*/
public static boolean getBoolean(Context context, String key) {
return context.getSharedPreferences("MusicCache", Context.MODE_PRIVATE)
.getBoolean(key, false);
}
/**
* 把对象保存在缓存中
*
* @param context
* @param object
*/
public static void putObject(Context context,String key, Object object) {
String value = Code(object);
context.getSharedPreferences("MusicCache", Context.MODE_PRIVATE).edit()
.putString(key, value).commit();
}
/**
* 把对象从缓存中取出来
*
* @param context
* @return
*/
public static Object getObject(Context context,String key) {
String code = context.getSharedPreferences("MusicCache",
Context.MODE_PRIVATE).getString(key,
null);
return Decode(code);
}
/**
* 编码
*
* @param object
* @return
*/
public static String Code(Object object) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
String code = null;
try {
ObjectOutputStream oos = new ObjectOutputStream(stream);
oos.writeObject(object);
code = new String(Base64.encodeBase64(stream.toByteArray()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
/**
* 解码
*
* @param code
* @return
*/
public static Object Decode(String code) {
if (code == null)
return null;
Object object = null;
byte[] base64 = Base64.decodeBase64(code.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(base64);
try {
ObjectInputStream bis = new ObjectInputStream(bais);
object = bis.readObject();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
/**
* 放入float 数据
* @param context
* @param key
* @param value
*/
public static void putFloat(Context context,String key,float value)
{
context.getSharedPreferences("MusicCache", Context.MODE_PRIVATE).edit()
.putFloat(key, value).commit();
}
/**
* 取出Float 值
* @param context
* @param key
* @return
*/
public static float getFloat(Context context,String key)
{
return context.getSharedPreferences("MusicCache", Context.MODE_PRIVATE)
.getFloat(key, 0);
}
}
注意:保存的对象必须是序列化的,我这边是实现了Serializable 类