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

    
    
  • 相关阅读:
    Selenium2+python自动化20-Excel数据参数化【转载】
    linux下安装jdk
    linux下的tomcat自动退出的问题
    操作笔记:tomcat在正式环境的常见问题和idea的远程调试
    Maven 的41种骨架
    ant风格是什么?
    tomcat 页面管理
    操作笔记:linux下查看端口被占用
    操作笔记:linux下安装ftp
    linux下的mysql乱码问题
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/10983315.html
Copyright © 2020-2023  润新知