DiskLruCache缓存bitmap
2024-08-27 22:49:52
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会出来这个依赖项
最新文章
- HDU5840 (分块+树链剖分)
- RAID磁盘阵列笔记
- 解剖SQLSERVER 完结篇 关于Internals Viewer源代码
- [ActionScript 3.0] AS3.0 复制xml,并赋值
- C++之路进阶——优先队列优化最短路径算法(dijkstra)
- apk反编译生成程序的源代码和图片、XML配置、语言资源等文件
- J2EE开发之常用开源项目介绍
- 闭包小demo
- ajax data属性传值的方式总结
- 快速实现office文档在线预览展示(doc,docx,xls,xlsx,ppt,pptx)
- jquery iCheck的全选和获取value
- gradle上传本地文件到远程maven库(nexus服务器)
- 18. 4Sum (通用算法 nSum)
- JS 为什么在涉及到模块开发this的时候使用类似 self = this 的形式 p7
- 007-配置IP和DNS
- js小数运算出现多位小数如何解决
- 笔记:PS 智能对象
- 完美配置Python3.5+Anaconda+PyQt5,实现UI和其他模块的结合
- SLF4J versions 1.4.0 and later requires log4j 1.2.12 or later 终极解决
- Android 透明状态栏