本地缓存DiskLruCache学习总结

本地缓存数据一般缓存在 /sdcard/Android/data/<application package>/cache,因为存储在SDK上,所以不会对手机内存空间产生影响,并且这个是Android系统认定的应用程序缓存路径,程序卸载的时候,这里的数据也会被一同清理掉。

创建DiskLruCache需要调用它的open(File directory,int appVersion,int valueCount,long maxSize)方法,不能直接new实例。

第一个指缓存地址,第二个是版本号,第三个是一个key可以缓存文件的个数,第四个是缓存的最多字节的数据。

开起一个DiskLruCache的方法:


DiskLruCache mDiskLruCache = null;
try {
	File cacheDir = getDiskCacheDir(context, "bitmap");
	if (!cacheDir.exists()) {
		cacheDir.mkdirs();
	}
	mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, 10 * 1024 * 1024);
} catch (IOException e) {
	e.printStackTrace();

在访问网络后传入的网址,通过outputStream写入到本地。写入操作接住DiskLruCache.Editor这个类来完成,一样不能通过new来实例化。需要调用DiskLruCache的edit()方法。

public Editor edit(String key) throws IOException

key成为缓存文件的文件名。注意文件名应和图片名字一样,需要编码为MD5。

public String hashKeyForDisk(String key) {
	String cacheKey;
	try {
		final MessageDigest mDigest = MessageDigest.getInstance("MD5");
		mDigest.update(key.getBytes());
		cacheKey = bytesToHexString(mDigest.digest());
	} catch (NoSuchAlgorithmException e) {
		cacheKey = String.valueOf(key.hashCode());
	}
	return cacheKey;
}
 
private String bytesToHexString(byte[] bytes) {
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < bytes.length; i++) {
		String hex = Integer.toHexString(0xFF & bytes[i]);
		if (hex.length() == 1) {
			sb.append('0');
		}
		sb.append(hex);
	}
	return sb.toString();

写入操作如下:

new Thread(new Runnable() {
	@Override
	public void run() {
		try {
			String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";
			String key = hashKeyForDisk(imageUrl);
			DiskLruCache.Editor editor = mDiskLruCache.edit(key);
			if (editor != null) {
				OutputStream outputStream = editor.newOutputStream(0);
				if (downloadUrlToStream(imageUrl, outputStream)) {
					editor.commit();
				} else {
					editor.abort();
				}
			}
			mDiskLruCache.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

读取缓存借助DiskLruCache的get()方法实现。

public synchronized Snapshot get(String key) throws IOException

其中key值为图片URL MD5编码后的值。

String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";
String key = hashKeyForDisk(imageUrl);
DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key)

读取到的是一个DiskLruCache.Snapshot对象。调用其getInputStream()方法得到缓存的输入流。


try {
	String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";
	String key = hashKeyForDisk(imageUrl);
	DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
	if (snapShot != null) {
		InputStream is = snapShot.getInputStream(0);
		Bitmap bitmap = BitmapFactory.decodeStream(is);
		mImage.setImageBitmap(bitmap);
	}
} catch (IOException e) {
	e.printStackTrace();
扫描二维码关注公众号,回复: 3572082 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_38256015/article/details/82218364