Android缓存Cache学习
项目中需要用到缓存,我使用的是文件缓存,这里简单总结下:
主要思路是封装一个缓存对象,将每个界面需要缓存的数据作为缓存对象的属性,将缓存对象以PageCache缓存到文件。
缓存对象类:
//封装缓存数据对象
public class PageCache implements Serializable {
private static final long serialVersionUID = 3405510521707227897L;
public static final String PAGE_KEY = "page.key";
// 缓存数据是集合
private List<BenqunItem> benqunList;
public List<BenqunItem> getBenqunList() {
return benqunList;
}
public void setBenqunList(List<BenqunItem> benqunList) {
this.benqunList = benqunList;
}
缓存工具类:
public class DataFileCache {
public static String FUJIN_CACHE_NAME = "A"; // 附近的人缓存目录
public static String BENQUN_CACHE_NAME = "B"; // 社群缓存目录
public static String BENYOU_CACHE_NAME = "C"; // 好友数据缓存目录
public static String USER_CACHE_NAME = "D"; // 个人页面缓存
public static final String CACHDIR = File.separator + "benben"
+ File.separator + "cache" + File.separator;// 缓存根目录
private static final String Suffix = ".benben";// 缓存文件后缀名
private static final int FREE_SD_SPACE_NEEDED_TO_CACHE = 1;// 缓存空间大于1M才能进行缓存
private int MB = 1024 * 1024;
private String folder = "";
public static final String Favorit_CACHE_NAME = "Favorit";
public static final String LOG_CACHE_NAME = "Log"; // 日志文件目录
public static final int Favorit_Key = 0x100;
public static final String Category_CACHE_NAME = "Category";
public static final int Category_Key = 0x101;//
private Context mContext;
/**
* @param folder
* 缓存目录文件夹
* */
public DataFileCache(Context context, String folder) {
this.folder = folder;
this.mContext = context;
}
/**
* 缓存数据
*