Android APP开发过程中,我们通常会加入缓存模块。缓存即在本地保存APP的一些数据,大部分是将网络请求的数据进行本地保存,这样在缓存数据有效期内就可以直接使用缓存数据,降低了APP和服务器的压力,也极大提升了用户体验。Android数据缓存既可以以数据表的形式进行保存,也可以以文件的形式进行缓存。这里我主要通过缓存文件存储数据,并在APP下一次启动时读取。
整个Cache模块的设计思想很简单,每个缓存数据都对应一个key,每个缓存数据又会被存到以此key命名的文件中,需要时直接读取。关键类分别为CacheData
, CacheManager
, CacheUtils
。
使用方法如下:
CacheManager.init(Context context)
, 在APP加载时就应该对CacheManager初始化。CacheUtils.java 主要用来存放一些常用变量
public class CacheUtils {
public final static String KEY_TEST = "key_test";
public final static long EXPIRATION_MINUTE = 60 * 1000;
public final static long EXPIRATION_HOUR = 60 * EXPIRATION_MINUTE;
public final static long EXPIRATION_DAY = 24 * EXPIRATION_HOUR;
public final static long EXPIRATION_WEEK = 7 * EXPIRATION_DAY;
}
CacheData.java 用来存储的数据结构
import java.io.Serializable;
public class CacheData<T> implements Serializable {
private long lastUpdated;
private String key;
private T data;
private long expiration;
public CacheData(String key, T data) {
this(key, data, -1);
}
public CacheData(String key, T data, long expiration) {
this.key = key;
this.expiration = expiration;
setData(data);
}
public void setData(T data) {
this.data = data;
this.lastUpdated = System.currentTimeMillis();
}
public boolean isValid() {
return expiration == -1 || lastUpdated + expiration > System.currentTimeMillis();
}
public String getKey() {
return key;
}
public T getData() {
return data;
}
}
CacheManager.java 读取与存储缓存
import android.content.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class CacheManager {
private static CacheManager instance;
private static Context mContext;
public static void init(Context context) {
mContext = context;
}
private CacheManager() {
}
public static CacheManager getInstance() {
if (instance == null) instance = new CacheManager();
return instance;
}
public void addCache(CacheData cacheData) {
if (cacheData == null) return;
try {
File file = new File(mContext.getCacheDir(), cacheData.getKey());
if (!file.exists()) {
file.createNewFile();
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(cacheData);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public CacheData getCache(String key) {
try {
File file = new File(mContext.getCacheDir(), key);
if (file == null) return null;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
CacheData cacheData = (CacheData) ois.readObject();
ois.close();
if (cacheData.isValid()) return cacheData;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
项目代码托管在Github Repo中,欢迎star和fork。
原文地址:http://blog.csdn.net/gongmingqm10/article/details/45009397