DiskLruCache bitmap caching

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  to false ; 
    } 
    Private  static  Final  int MAX_SIZE = 10 * 1024 * 1024; // most cache 10MB, the minimum unit of byte 
    Private  void initDiskLruCache () {
         IF (diskLruCache == null || diskLruCache.isClosed ()) {
             the try { 
                cacheDir is File = getDiskCacheDir ( the this , ", mycache" );
                 IF (! {cacheDir.exists ()) 
                    cacheDir.mkdirs (); 
                } 
                // initialize 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 ) { 
                the OutputStream the outputStream = editor.newOutputStream (0 );
                 IF (downloadUrlToStream (URI, the outputStream)) {
                     // write cache 
                    editor.commit (); 
                } the else {
                     / / write failure 
                    editor.abort (); 
                } 
            } 
            diskLruCache.flush (); 
         handler.sendEmptyMessage ( . 1 ); 
        } the catch (IOException E) { 
            e.printStackTrace ();
 
        } 

    } 
  }; 

    public  static String hashKeyForDisk (String Key) { 
        String cacheKey; 
        the try {
             Final the MessageDigest mDigest = MessageDigest.getInstance ( "the MD5"); // the uri compiled MD5, and the URL to prevent illegal character 
            mDigest.update (key.getBytes ()); 
            cacheKey = bytesToHexString (mDigest.digest ()); 
        } the 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() {
        the try {
            Snapshot DiskLruCache.Snapshot = diskLruCache.get (Key); // get the buffer by Key 
            IF (Snapshot =! Null ) { 
                the InputStream in = snapshot.getInputStream (0); // get a stream input operation 
                return BitmapFactory.decodeStream (in ); 
            } 
        } the catch (IOException E) { 
            e.printStackTrace (); 
        } 
        return  null ; 
    } 
@SuppressLint ( "HandlerLeak" ) 
Handler Handler = new 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 is the second-level cache, you need to add dependencies,

implementation 'com.jakewharton: disklrucache: 2.0.2' 
press alt + enter will be prompt

Right-module Open module settings, dependencies search DiskLrucache will come out of this dependency

Guess you like

Origin www.cnblogs.com/Ocean123123/p/10983315.html