DiskLruCache学习
2016-06-19 23:43
288 查看
DiskLruCache认识
可以将从网络获取的图片存储在本地磁盘中,减少内存存储的大小一般存储位置为:
/sdcard/Android/data/application package/cache
DiskLruCach下载地址
下载
获取DiskLruCach实例获取:
DiskLruCache.open(cacheDir,getAppVersion(this),1,10 * 1024 * 1024);
第一个参数是缓存地址一般就在这个位置/sdcard/Android/data/application package/cache,
第二个参数是app的版本号码(当版本号码改变时所有数据会被清理)
第三个参数是每一个key对应几个缓存文件
第四个参数是缓存的大小
获取缓存路径:
当sd卡存在时使用getExternalCacheDir()方法获取缓存路径( /sdcard/Android/data/application package/cache)
否则使用getCacheDir()(/data/data/application package>cache )
获取缓存路径后需要加上在路径后面拼接上一个字符串uniqueName(为了对不同数据进行区分而设定的唯一值)
写缓存:
private boolean downloadUrlToStream(String urlString, OutputStream outputStream){ HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(),8 * 1024); out = new BufferedOutputStream(outputStream,8 * 1024); int b; while ((b = in.read()) != -1){ out.write(b); } return true; } catch (IOException e) { e.printStackTrace(); }finally { if(urlConnection != null){ urlConnection.disconnect(); } try { if(out != null){ out.close(); } if(in != null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } return false; }
DiskLruCache.Editor的实例:
用来写入缓存
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
//下载图片 new Thread(){ @Override public void run() { try { String imageUrl = "http://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1664915200,467145583&fm=80"; 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();//放弃本次写入 } } } } catch (IOException e) { e.printStackTrace(); } } }.start(); }
获取缓存:
DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
if(snapshot != null){ InputStream is = snapshot.getInputStream(0); final Bitmap bitmap = BitmapFactory.decodeStream(is); runOnUiThread(new Runnable() { @Override public void run() { img.setImageBitmap(bitmap); } });
删除
mDiskLruCache.remove(key);
相关文章推荐
- Java Notes-15(Proxies, RIM)
- redis学习domo
- MySQL各逻辑模块工作配合
- Java基础篇(一)-----计算器
- redis安装
- Android Volley增加Https支持,允许SSL
- sysfs: duplicate filename 's3c2440-nand' can not be created。linux2.6的内核编译中出现的问题
- 敏捷估计与规划
- C++:运算符重载
- UVa 1374 Power Calculus (IDA*或都打表)
- 内核挂载文件系统的几种方式
- C#复习⑤
- bootstrap之双日历时间段选择控件Date Range Picker
- 客户端同步服务器时间
- 设计模式总结
- 程序、技术、潮流与时尚
- 程序、技术、潮流与时尚
- 项目菜鸟成长为老鸟之路
- php_memcache 缓存 下载-安装-配置-学习
- Android:文件下载和写入SD卡