您的位置:首页 > 其它

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: