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的更多相关文章

  1. DiskLruCache和Lrucache缓存bitmap

    三级缓存,先在内存Lrucache中查找缓存,没有就去外存DiskLrucache中查找,再没有就下载,Lru不会自动删除,所以要设置最大缓存内存,后台运行Lrucache不会消失,关闭程序Diskl ...

  2. android 缓存Bitmap - 开发文档翻译

    由于本人英文能力实在有限,不足之初敬请谅解 本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接链接 Loading a single bitmap into your user interf ...

  3. LruCache DiskLruCache 缓存 简介 案例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  4. 综合使用LruCache和DiskLruCache 缓存图片

    Activity public class MainActivity extends Activity {     private GridView mPhotoWall;     private P ...

  5. android 缓存Bitmap 使用内存缓存

    private LruCache<String, Bitmap> mMemoryCache; /** * 判断内存大小 设置位图的缓存空间 */ private void judgeMem ...

  6. LruCache缓存bitmap(二)

    Lrucache缓存程序关闭缓存自动清除,所以要在onstart方法中调用,只要不关闭程序缓存就在,除以1024是以kb为单位 public class MainActivity extends Ap ...

  7. LruCache缓存bitmap(一)

    Lrucache是把图片缓存到内置sd卡,设置缓存容量为系统分配容量的八分之一,单位byte,超过缓存容量gc会自动回收不长使用的缓存.觉得lrucache就先map一样,放入键值对就行了,比较方便, ...

  8. LruCache缓存bitmap(三)

    应用在网络连接上,onrestart后不会重新联网获取图片,省去了流量, public class MainActivity extends AppCompatActivity { ImageView ...

  9. Android硬盘缓存技术DiskLruCache技术笔记

    防止多图OOM的核心解决思路就是使用LruCache技术,但LruCache只是管理了内存中图片的存储与释放,如果图片从内存中被移除的话,那么又需要从网络上重新加载一次,这显然非常耗时.因此Googl ...

随机推荐

  1. keras中的mask操作

    使用背景 最常见的一种情况, 在NLP问题的句子补全方法中, 按照一定的长度, 对句子进行填补和截取操作. 一般使用keras.preprocessing.sequence包中的pad_sequenc ...

  2. Processing 状态量控制动画技巧

    之前在CSDN上发表过: https://blog.csdn.net/fddxsyf123/article/details/62848357

  3. 2020 CiGA Game Jam活动总结

    CiGA Game Jam 总结 今年8月14.15.16号,48小时游戏开发--Game Jam开始了.蠢新第一次参加Game Jam,今年还是线上开展,情绪复杂= = 还有一个坏消息,晓航旅游缺席 ...

  4. Python练习题 010:分解质因数

    [Python练习题 010]将一个正整数分解质因数.例如:输入90,打印出90=2*3*3*5. -------------------------------------------------- ...

  5. [Vue warn]: Error in render: "TypeError: Cannot read property 'matched' of undefined" found in <App> at src/App.vue

    当用Vue模块化开发时,输入  http://localhost:8080  页面没有显示,首先按F12,检查是否有如下错误 话不多说,直接看下面: 解决方法1 如果是上面出的问题,以后就要注意了哦, ...

  6. 【Python】数据结构

    列表的更多特性 list.append(x) 在列表的末尾添加一个元素.相当于 a[len(a):] = [x] . list.extend(iterable) 使用可迭代对象中的所有元素来扩展列表. ...

  7. Pyinstaller打包通用流程

    Pyinstaller打包通用流程 前言 什么是Pyinstaller Pyinstaller是用于打包python项目的一个工具, 可以将项目代码打包成可执行文件, 在其他机器上使用. 通俗的说, ...

  8. SQL实战——04. 查找所有已经分配部门的员工的last_name和first_name以及dept_no (一个逗号引发的血案)

    查找所有已经分配部门的员工的last_name和first_name以及dept_noCREATE TABLE `dept_emp` (`emp_no` int(11) NOT NULL,`dept_ ...

  9. keepass+坚果云管理我的密码

    目录 前言 下载安装KeePass 创建一个数据库 配置坚果云 手机用坚果云 总结 前言     KeePass是一款免费.小巧.绿色且开源的密码管理工具,多年来一直深受大众的好评,它能为用户提供一个 ...

  10. matlab中for 用来重复指定次数的 for 循环

    参考:https://ww2.mathworks.cn/help/matlab/ref/for.html?searchHighlight=for&s_tid=doc_srchtitle for ...