Use Cases of Andriod DiskLruCache
DiskLruCache is a class recommended by Google to implement hard disk cache. In this case, we will summarize the basic usage of DiskLruCache, including creating cache, searching and using cache, and removing cache.
Implementation
Create DiskLruCache
DiskLruCache uses the open method to create an instance, as shown in the following figure. The four parameters are respectively the cache directory, application version number, and the number of data corresponding to a single key (generally set to 1), the total cache size, where the key is obtained by the image url after MD5 transcoding, to prevent the normal use of the cache from being affected by the url with special symbols.
try { File cacheDir = getDiskCacheDir(this, "bitmap"); if (!cacheDir.exists()) { cacheDir.mkdirs(); } mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(this), 1, 10 * 1024 * 1024); } catch (Exception e) { e.printStackTrace(); }
Storage cache
You can use DiskLruCache. Editor to obtain the editor of the cache object, which is similar to the editor of SharedPreference. DiskLruCache does not allow editing a cache object at the same time. If the cached object is being edited, editor = null.
New Thread (new Runnable () {@ Override public void run () {try {String key = hashKeyForDisk (imageUrl); DiskLruCache. editor editor = null; editor = mDiskLruCache. edit (key); if (editor! = Null) {OutputStream outputStream = editor. newOutputStream (0); if (downloadUrlToStream (imageUrl, outputStream) {editor. commit ();} else {editor. abort () ;}// do not flush frequently to prevent frequent modification of mDiskLruCache in journal log files. flush (); handler. post (new Runnable () {@ Override public void run () {textView. setText ("saveCache done, the bitmap is ready") ;}});} catch (IOException e) {e. printStackTrace ();}}}). start ();
Read Cache
The DiskLruCache. get (String key) method can obtain a Snapshot instance. The input stream of the cached file is obtained through the DiskLruCache. Snapshot instance, and the image is displayed on the imageView.
// Read cache try {DiskLruCache. Snapshot snapshot = mDiskLruCache. get (hashKeyForDisk (imageUrl); if (snapshot! = Null) {InputStream is = snapshot. getInputStream (0); Bitmap bitmap = BitmapFactory. decodeStream (is); imageView. setImageBitmap (bitmap);} else {imageView. setImageBitmap (null) ;}} catch (IOException e) {e. printStackTrace ();}
In addition, DiskLruCache also provides methods such as clearing the cache delete (), obtaining the cache size () in the cache directory, and so on.