此方式可以保存将对象持久化到SharedPreferences,存储的对象需要实现Serializable接口。
private static SharedPreferences sPref;
private static SharedPreferences getPreference(Context ctx) {
if (sPref == null) {
sPref = ctx.getApplicationContext()
.getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
}
return sPref;
}
private static Editor getEditor(Context ctx) {
return getPreference(ctx).edit();
}
private static void writeObject(Context ctx, String key, Object obj) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
String objBase64 = new String(Base64.encode(baos.toByteArray()));
getEditor(ctx).putString(key, objBase64).commit();
} catch (Exception e) {
Log.e("test", "saveObject error", e);
}
}
private static Object readObject(Context ctx, String key) {
try {
String objBase64 = getPreference(ctx).getString(key, null);
if (TextUtils.isEmpty(objBase64)) {
return null;
}
byte[] base64 = Base64.decode(objBase64);
ByteArrayInputStream bais = new ByteArrayInputStream(base64);
ObjectInputStream bis = new ObjectInputStream(bais);
return bis.readObject();
} catch (Exception e) {
Log.e("test", "readObject error", e);
}
return null;
}