DiskLruCache缓存bitmap
- public class MainActivity extends AppCompatActivity {
private DiskLruCache diskLruCache;
ImageView imageView;
String key;
String uri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.image);
File file = getDiskCacheDir(this, "a");
System.out.println(file.getAbsolutePath() + "缓存路径");
initDiskLruCache();
Bitmap bitmap = getCache();
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
new Thread(runnable).start();
}
}
public static File getDiskCacheDir(Context context, String uniqueName) {
final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||!Environment.isExternalStorageRemovable()
? context.getExternalCacheDir().getPath()
: context.getCacheDir().getPath();
return new File(cachePath + File.separator + 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());
out = new BufferedOutputStream(outputStream);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (Exception e) {
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {
}
}
return false;
}
private static final int MAX_SIZE = 10 * 1024 * 1024;//最多缓存10MB,最小单位byte
private void initDiskLruCache() {
if (diskLruCache == null || diskLruCache.isClosed()) {
try {
File cacheDir =getDiskCacheDir(this, "mycache");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
//初始化DiskLruCache
diskLruCache = DiskLruCache.open(cacheDir, 1, 1, MAX_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Runnable runnable=new Runnable() {
@Override
public void run() {
try {
//得到DiskLruCache.Editor
DiskLruCache.Editor editor = diskLruCache.edit(key);
if (editor != null) {
OutputStream outputStream = editor.newOutputStream(0);
if (downloadUrlToStream(uri, outputStream)) {
//写入缓存
editor.commit();
} else {
//写入失败
editor.abort();
}
}
diskLruCache.flush();
handler.sendEmptyMessage(1);
} catch (IOException e) {
e.printStackTrace();
}
}
};
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");//把uri编译为MD5,防止网址有非法字符
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
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();
}
private Bitmap getCache() {
try {
uri = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3166403788,4188649647&fm=115&gp=0.jpg";
key = hashKeyForDisk(uri);
DiskLruCache.Snapshot snapshot = diskLruCache.get(key);//通过key得到缓存
if (snapshot != null) {
InputStream in = snapshot.getInputStream(0);//得到一个输入流进行操作
return BitmapFactory.decodeStream(in);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@SuppressLint("HandlerLeak")
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Bitmap bitmap = getCache();
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
};
}
DiskLrucache是第二级缓存,缓存到外置sd卡,需要添加依赖,需要读取外置sd卡权限
- implementation 'com.jakewharton:disklrucache:2.0.2'
按alt+enter会有提示
右键module打开module设置,依赖项搜索DiskLrucache会出来这个依赖项
DiskLruCache缓存bitmap的更多相关文章
- DiskLruCache和Lrucache缓存bitmap
三级缓存,先在内存Lrucache中查找缓存,没有就去外存DiskLrucache中查找,再没有就下载,Lru不会自动删除,所以要设置最大缓存内存,后台运行Lrucache不会消失,关闭程序Diskl ...
- android 缓存Bitmap - 开发文档翻译
由于本人英文能力实在有限,不足之初敬请谅解 本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接链接 Loading a single bitmap into your user interf ...
- LruCache DiskLruCache 缓存 简介 案例 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- 综合使用LruCache和DiskLruCache 缓存图片
Activity public class MainActivity extends Activity { private GridView mPhotoWall; private P ...
- android 缓存Bitmap 使用内存缓存
private LruCache<String, Bitmap> mMemoryCache; /** * 判断内存大小 设置位图的缓存空间 */ private void judgeMem ...
- LruCache缓存bitmap(二)
Lrucache缓存程序关闭缓存自动清除,所以要在onstart方法中调用,只要不关闭程序缓存就在,除以1024是以kb为单位 public class MainActivity extends Ap ...
- LruCache缓存bitmap(一)
Lrucache是把图片缓存到内置sd卡,设置缓存容量为系统分配容量的八分之一,单位byte,超过缓存容量gc会自动回收不长使用的缓存.觉得lrucache就先map一样,放入键值对就行了,比较方便, ...
- LruCache缓存bitmap(三)
应用在网络连接上,onrestart后不会重新联网获取图片,省去了流量, public class MainActivity extends AppCompatActivity { ImageView ...
- Android硬盘缓存技术DiskLruCache技术笔记
防止多图OOM的核心解决思路就是使用LruCache技术,但LruCache只是管理了内存中图片的存储与释放,如果图片从内存中被移除的话,那么又需要从网络上重新加载一次,这显然非常耗时.因此Googl ...
随机推荐
- ES6 常用总结——第二章(字符串的扩展)
ES6为字符串添加了遍历器接口,使得字符串可以被for...of循环遍历. for (let codePoint of 'foo') { console.log(codePoint)} // &quo ...
- Java 内存模型(Java Memory Model,JMM)
基本概念 JMM 本身是一种抽象的概念并不是真实存在,它描述的是一组规范,通过这组规范定义了程序的访问方式 JMM 同步规定 线程解锁前,必须把共享变量的值刷新回主内存 线程加锁前,必须读取主内存的最 ...
- JVM学习(一)什么是JVM
一.初识JVM(虚拟机) JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功 ...
- 图形渲染的大致过程和关于OpenGL渲染管线的一些零碎知识,openglpipeline,vao,vbo,ebo.
重要!!! OpenGL新人一枚,希望可以再此和大家分享有用的知识,少走弯路 文章会定期更新,把前面几段已经整理过的知识更完后,接下来每周至少会更两次. 文章如果有不对的,理解错误的地方,也非常希望在 ...
- Oracle 中 Start With 关键字
Start With (树查询) 基本语法如下: SELECT ... FROM + 表名 WHERE + 条件3 START WITH + 条件1 CONNECT BY PRIOR + 条件2 -- ...
- Django-Scrapy生成后端json接口
Django-Scrapy生成后端json接口: 网上的关于django-scrapy的介绍比较少,该博客只在本人查资料的过程中学习的,如果不对之处,希望指出改正: 以后的博客可能不会再出关于djan ...
- jQuery中使用$.each()遍历数组时要注意的地方
使用jQuery中 $.each()遍历数组,要遍历的数组不能为空(arry!="") 例如: $.each(arry, function (i, item) ...
- 手把手撸套框架-Victory框架1.0 详解
目录 其实Victory框架1.0 在8月份就完成了,整个9月份都没有更新博客,主要还是因为松懈了. 所以,趁着国庆节的放假的时间把博客给更新一下,1.0总的来说算不得一个成熟的产品,但是拿来开发我们 ...
- Linux安装软件方法总结
相比于windows系统,Linux安装程序就比较复杂了,很多需要root用户才能安装.常见的有以下几种安装方法 源码安装 rpm包安装 yum安装 (RedHat.CentOS) apt-get安装 ...
- 插头 dp
插头dp 洛谷 黑题板子? P5056 给出n×m的方格,有些格子不能铺线,其它格子必须铺,形成一个闭合回路.问有多少种铺法? 1.轮廓线 简单地说,轮廓线就是已决策格子和未决策格子的分界线: 2,插 ...