Disklrucache is the class that Google recommends to implement the hard disk cache, this case will be a summary of the basic usage of Disklrucache, including: Create cache, find use cache, remove cache and so on.
Realize
Create Disklrucache
Disklrucache uses the Open method to create an instance, such as the following: the corresponding four parameters are: Cache folder, application version, the number of corresponding data of a single key (generally set to 1), the total size of the cache, where key is the URL of the image is obtained by MD5 transcoding, Prevent URLs with special symbols that affect the normal use of the cache.
try { File cacheDir = getDiskCacheDir(this"bitmap"); if (!cacheDir.exists()) { cacheDir.mkdirs(); } mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(this11010241024); catch (Exception e) { e.printStackTrace(); }
Storage cache
Edit Object Editor, similar to Sharedpreference, can be obtained by Disklrucache.editor to the cache object. Disklrucache does not agree to edit a cache object at the same time. Assuming that the cached object is being edited, it is editor==null.
NewThread (NewRunnable () {@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 (); } }//should not flush frequently to prevent frequent changes to journal log filesMdisklrucache.flush (); Handler.post (NewRunnable () {@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 is able to obtain an snapshot instance that obtains the input stream of the cached file through the Disklrucache.snapshot instance. You can display the picture on the ImageView.
//读取缓存 try { DiskLruCache.Snapshot snapshot = mDiskLruCache.get(hashKeyForDisk(imageUrl)); ifnull) { is = snapshot.getInputStream(0); Bitmap bitmap = BitmapFactory.decodeStream(is); imageView.setImageBitmap(bitmap); else { imageView.setImageBitmap(null); } catch (IOException e) { e.printStackTrace(); }
Other than that. Disklrucache also provides methods such as emptying the cache delete (), obtaining cache size under the cache folder, and so on to manipulate the cache.
This case source code includes the basic usage of disklrucache, click Download.
Use cases of Andriod Disklrucache