在Android开发过程中,往往会用到缓存,我们今天所讲的就是有关请求网络数据后的缓存,相关的技术有很多,比如利用三方库greendao、ormlite,这两种属于orm(对象关系映射(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping)),详细的两者使用方式以及优缺点这里不加描述,感兴趣的可以自行搜索,用retrofit那一套框架的同学,可能还会用到retrofit自带的缓存技术,相关技术我在之前的文章中也有所讲到(http://blog.csdn.net/qqyanjiang/article/details/51316116)。
但是,我们今天所分析的是特别轻量级的缓存技术——ACache,为什么说它特别特别轻量级呢,因为代码少到只有一个类,用起来也极其方便,也是专门为Android量身定制的缓存框架,你可以随意的定义缓存路径、过期时间、缓存大小、数量等,下面开始我们的表演。
Acache(https://github.com/yangfuhai/ASimpleCache)
没错,它的作者就是国内知名框架Afinal的作者。final的几个常量注释上有介绍,这里不细说。
public static ACache get(Context ctx) {
return get(ctx, "ACache");
}
public static ACache get(Context ctx, String cacheName) {
File f = new File(ctx.getCacheDir(), cacheName);
return get(f, MAX_SIZE, MAX_COUNT);
}
public static ACache get(File cacheDir) {
return get(cacheDir, MAX_SIZE, MAX_COUNT);
}
public static ACache get(Context ctx, long max_zise, int max_count) {
File f = new File(ctx.getCacheDir(), "ACache");
return get(f, max_zise, max_count);
}
public static ACache get(File cacheDir, long max_zise, int max_count) {
ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
if (manager == null) {
manager = new ACache(cacheDir, max_zise, max_count);
mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
}
return manager;
}
这里很简单,前4个get方法最终都调用了最后一个get,所以我们只分析最后一个方法就ok。如果manager为null,则new ACache的实例manager,然后将缓存路径+进程id作为key,存入到mInstanceMap中;如果manger不为空,则直接从map中通过kye去获取。
private ACache(File cacheDir, long max_size, int max_count) {
if (!cacheDir.exists() && !cacheDir.mkdirs()) {
throw new RuntimeException("can't make dirs in " + cacheDir.getAbsolutePath());
}
mCache = new ACacheManager(cacheDir, max_size, max_count);
}
以上是ACache构造函数,会实例一个缓存管理器mCache(下面做介绍)。通过ACache.get方法就可以轻松的获取到ACache的实例,实例有了,下面介绍下如何调用方法吧。
public void put(String key, String value) {
File file = mCache.newFile(key);
BufferedWriter out = null;
try {
/**
* 为了提高写入的效率,使用了字符流的缓冲区。
* 创建了一个字符写入流的缓冲区对象,并和指定要被缓冲的流对象相关联。
*/
out = new BufferedWriter(new FileWriter(file), 1024);
out.write(value); //使用缓冲区中的方法将数据写入到缓冲区中。
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();//使用缓冲区中的方法,将数据刷新到目的地文件中去。
out.close(); //关闭缓冲区,同时关闭了fw流对象
} catch (IOException e) {
e.printStackTrace();
}
}
mCache.put(file);
}
}
newFile是管理类的方法,所以我们到内部类ACacheManager中去查看方法,
private File newFile(String key) {
return new File(cacheDir, key.hashCode() + "");
}
只是很简单调用了new File方法,然后我们使用缓冲的字符输入流将数据写入缓冲区中。
ACache mCache=ACache.get(this);
mCache.put();
mCache.put();