DiskLruCache缓存bitmap

public class MainActivity extends AppCompatActivity  {
    private DiskLruCache diskLruCache;
    ImageView imageView;
    String key;
    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();
        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);
            }
            out.flush();
            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 {
         String uri = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3166403788,4188649647&fm=115&gp=0.jpg";
           key = hashKeyForDisk(uri);
            //得到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 {
            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是第二级缓存,需要添加依赖,

implementation 'com.jakewharton:disklrucache:2.0.2'
按alt+enter会有提示

右键module打开module设置,依赖项搜索DiskLrucache会出来这个依赖项

猜你喜欢

转载自www.cnblogs.com/Ocean123123/p/10983315.html
今日推荐