/**
* Project_name:TaobaoUnion
* Created by:ChenFuXu.
* Date: 2022/3/20 20:07
*
* 缓存工具类
*/
public class JsonCacheUtil {
public static final String JSON_CACHE_SP_NAME = "json_cache_sp_name";
private static volatile JsonCacheUtil sJsonCacheUtil = null;
private final SharedPreferences mSharedPreferences;
private final Gson mGson;
private JsonCacheUtil() {
mSharedPreferences = BaseApplication.getAppContext().getSharedPreferences(JSON_CACHE_SP_NAME
, Context.MODE_PRIVATE);
mGson = new Gson();
}
public static JsonCacheUtil getInstance() {
if (sJsonCacheUtil == null) {
synchronized (JsonCacheUtil.class) {
if (sJsonCacheUtil == null) {
sJsonCacheUtil = new JsonCacheUtil();
}
}
}
return sJsonCacheUtil;
}
// 增加数据
public void saveCache(String key, Object value) {
this.saveCache(key, value, -1);
}
/**
*
* @param key
* @param value
* @param duration 表示设置的缓存的时间
*/
public void saveCache(String key, Object value, long duration) {
SharedPreferences.Editor edit = mSharedPreferences.edit();
// 将对象转成字符串
String valueStr = mGson.toJson(value);
if (duration != -1L) {
/**
* 比如设置的缓存的时间为100s,那么100s后过期
* 这里加上当前的系统时间
*/
duration += System.currentTimeMillis();
}
CacheDuration cacheDuration = new CacheDuration(duration, valueStr);
String cacheDurationStr = mGson.toJson(cacheDuration); // 转成字符串
edit.putString(key, cacheDurationStr);
edit.apply();
}
// 删除数据
public void delCache(String key) {
mSharedPreferences.edit().remove(key).apply();
}
// 获取数据
public <T extends Class> T getValue(String key, Class<T> clazz) {
String valueWithDuration = mSharedPreferences.getString(key, null);
if (valueWithDuration == null) {
return null;
}
CacheDuration cacheDuration = mGson.fromJson(valueWithDuration, CacheDuration.class);
long duration = cacheDuration.getDuration();
// 此处减去当前的系统时间,如果大于0,表示未超时,小于0,表示缓存时间已到
if (duration != -1L && (duration - System.currentTimeMillis()) < 0) {
// 过期了
return null;
} else {
// 未过期
// 获取缓存的内容字符串
String cacheStr = cacheDuration.getCache();
// 转为对象
return mGson.fromJson(cacheStr, clazz);
}
}
}
可以用来缓存对象,duration为设置需要缓存的时间