• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Ocean123123
博客园    首页    新随笔    联系   管理    订阅  订阅

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会出来这个依赖项


posted @ 2019-06-06 09:52  Ocean123123  阅读(289)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3