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. java代码复用(继承,组合以及代理)

    作为一门面向对象开发的语言,代码复用是java引人注意的功能之一.java代码的复用有继承,组合以及代理三种具体的表现形式,下面一一道来. 第一种方式是通过按照现有的类的类型创建新类的方式实现代码的复 ...

  2. Java中的常见锁(公平和非公平锁、可重入锁和不可重入锁、自旋锁、独占锁和共享锁)

    公平和非公平锁 公平锁:是指多个线程按照申请的顺序来获取值.在并发环境中,每一个线程在获取锁时会先查看此锁维护的等待队列,如果为空,或者当前线程是等待队列的第一个就占有锁,否者就会加入到等待队列中,以 ...

  3. 二分类问题续 - 【老鱼学tensorflow2】

    前面我们针对电影评论编写了二分类问题的解决方案. 这里对前面的这个方案进行一些改进. 分批训练 model.fit(x_train, y_train, epochs=20, batch_size=51 ...

  4. 手写:javascript中的关键字new

    简单介绍一下new new再熟悉不过了,new后面跟着构造函数,可以创建对象,这个对象的原型指向构造函数的原型对象,说起来可能有点绕,直接看代码吧 function Person(name, age) ...

  5. 刷题[GXYCTF2019]禁止套娃

    梳理思路 打开网站,发现很简单,只有flag在哪里的字样. 查看源码,常用后台目录,robots.txt,都未发现有任何东西. 扫描 直接拉进扫描器一扫,发现 思考可能是git源码泄露,可能可以恢复源 ...

  6. Spring及tomcat初始化日志

    Tomcat StandardContext初始化过程 //org.apache.catalina.core.StandardContext#startInternal // 子容器启动 for (C ...

  7. mysqldump 5.7

    简介 mysqldump是官方自带的文本格式备份工具,简单实用,一般在Mysql安装目录的bin目录下.备份文件默认是SQL格式,它由一系列语句例如CREATE TABLE.INSERT等组成.mys ...

  8. 微信小程序-简介

    微信小程序定位 1. 不需要下载安装即可使用 2. 用户用完即走,不用关系是否安装太多应用 3. 应用无处不在,随时可用 # 不要安装可使用是个伪命题,因为小程序的安装包小于1M,下载安装到使用的过程 ...

  9. 在.NET中使用DiagnosticSource

    前言 DiagnosticSource是一个非常有意思的且非常有用的API,对于这些API它们允许不同的库发送命名事件,并且它们也允许应用程序订阅这些事件并处理它们,它使我们的消费者可以在运行时动态发 ...

  10. 【字符串算法】AC自动机

    国庆后面两天划水,甚至想接着发出咕咕咕的叫声.咳咳咳,这些都不重要!最近学习了一下AC自动机,发现其实远没有想象中的那么难. AC自动机的来历 我知道,很多人在第一次看到这个东西的时侯是非常兴奋的.( ...