Android Disklrucache full parsing, hard disk caching best practices

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/28863651

Overview

Remember in a very early time, I have written an article Android efficient loading large map, multi-figure solution, effectively avoid the program Oom, this article is translated from the Android doc, which prevents multi-image oom core solution is to use LRUCache technology. But LRUCache only manages the storage and release of images in memory, and if the images are removed from memory, then it is obviously time-consuming to reload the image from the network. In this, Google also provides a set of hard disk caching solutions: Disklrucache (not officially written by Google, but obtained official certification). Unfortunately, the Android doc does not give a detailed description of the use of Disklrucache, and the online information about Disklrucache is very few, so today I am prepared to write a blog to explain in detail the use of Disklrucache, and analyze how it works, this should also be the most detailed information about Disklrucache on the internet now.

So let's take a look at what applications already use Disklrucache technology. In the range of applications I have contacted, Dropbox, Twitter, NetEase news, etc. are all using Disklrucache for hard disk caching, and most of Dropbox and Twitter are useless, so we start with the most familiar NetEase news. Come and have an initial understanding of Disklrucache.

Of

I believe everyone knows that the data in NetEase news is obtained from the Internet, including a lot of news content and news pictures, as shown in:


But I don't know if anyone has found out that the content and images are stored in the local cache after being fetched from the web, so even if the phone is not in the network, it can still load the previously browsed news. And the use of the cache technology does not have to say, the natural is Disklrucache, then the first question, the data are slow to exist where the phone?

In fact, Disklrucache does not restrict the cache location of the data, it can be set freely, but most of the applications will typically choose the location of the cache as/sdcard/android/data/<application package>/ The cache path. There are two benefits in this location: First, this is stored on the SD card, so even if the cache of more data will not have any impact on the phone's built-in storage space, as long as the SD card space is enough. Second, the path is identified by the Android system as the application's cache path, and when the program is uninstalled, the data will be erased together, so there will be no more residual data on the phone after the removal process.

So here or NetEase news For example, its client's package name is com.netease.newsreader.activity, so the data cache address should be/sdcard/android/data/ Com.netease.newsreader.activity/cache, let's go into this directory and look at the results as shown:


Can see a lot of folders, because NetEase news on a variety of types of data are cached, here for the sake of simplicity we only analyze the picture cache, so go into the bitmap folder. Then you will see a bunch of files with a long file name, these files are named without any rules, they don't really understand what it means, but if you scroll down all the time, you'll see a file named Journal, as shown in:


So what exactly are these files? See here to believe that some friends are already confused, here I briefly explain. Those files with long file names above are a picture of the cache, each file corresponds to a picture, and the journal file is a log file of Disklrucache, the program for each image of the operation records are stored in this file, Basically seeing journal this file marks the program's use of Disklrucache technology.

Download

Well, after the initial understanding of Disklrucache, let's learn how to use Disklrucache. Since Disklrucache is not written by Google, the class is not included in the Android API, and we need to download the class from the web and add it to the project manually. Disklrucache source on Google Source, the address is as follows:

Android.googlesource.com/platform/libcore/+/jb-mr2-release/luni/src/main/java/libcore/io/disklrucache.java

If Google source does not open, you can also click here to download Disklrucache source code. Once you have downloaded the source code, simply create a new Libcore.io package in your project and copy the Disklrucache.java file into this package.

Open cache

In that case we'll get the preparation done, and let's look at how Disklrucache should be used. First you know that Disklrucache is not new to the instance, and if we are going to create an instance of Disklrucache, we need to call its open () method, as shown in the interface below:

public static Disklrucache open (File directory, int appversion, int valuecount, long maxSize)
The open () method receives four parameters, the first parameter specifies the cached address of the data, the second parameter specifies the version number of the current application, the third parameter specifies how many cache files the same key can correspond to, the basic is 1, and the fourth parameter specifies the maximum number of bytes of data that can be cached.

Where the cache address has been said before, usually will be stored in the/sdcard/android/data/<application package>/cache this path, but at the same time we need to consider if this phone does not have an SD card, Or the SD is just removed, so a good program will write a method to get the cache address as follows:

Public File Getdiskcachedir (context context, string uniqueName) {string cachepath;if (Environment.MEDIA_MOUNTED.equals (Environment.getexternalstoragestate ()) | | ! Environment.isexternalstorageremovable ()) {CachePath = Context.getexternalcachedir (). GetPath ();} else {CachePath = Context.getcachedir (). GetPath ();} return new File (CachePath + file.separator + uniqueName);}
As you can see, when the SD card is present or the SD card is not removable, call the Getexternalcachedir () method to get the cache path, otherwise call the Getcachedir () method to get the cache path. The former obtains the/sdcard/android/data/<application Package>/cache this path, the latter obtains is the/data/data/<application package >/cache this path.

The acquired path is then spliced with a uniquename, which is returned as the final cache path. So what is this uniquename? In fact, this is to distinguish between different types of data set a unique value, such as in the NetEase news cache path to see the bitmap, object and other folders.

followed by the application version number, we can easily get the version number of the current application using the following code:

public int Getappversion (context context) {try {packageinfo info = Context.getpackagemanager (). Getpackageinfo ( Context.getpackagename (), 0); return info.versioncode;} catch (Namenotfoundexception e) {e.printstacktrace ();} return 1;}
It is important to note that whenever the version number changes, all the data stored in the cache path is erased because Disklrucache believes that when the application has a version update, all the data should be retrieved from the Web.

The next two parameters there is nothing to explain, the third parameter to 1, the fourth parameter is usually passed 10M size is enough, this can be adjusted according to their own circumstances.

Therefore, a very standard open () method can be written like this:

Disklrucache Mdisklrucache = null;try {File Cachedir = Getdiskcachedir (Context, "Bitmap"); if (!cachedir.exists ()) { Cachedir.mkdirs ();} Mdisklrucache = Disklrucache.open (Cachedir, getappversion (context), 1, 10 * 1024 * 1024);} catch (IOException e) {e.printstacktrace ();}
First call the Getdiskcachedir () method to get the path to the cache address, and then determine if the path exists and create it if it does not exist. Then call Disklrucache's Open () method to create the instance and pass four parameters.

With the example of Disklrucache, we can manipulate the cached data, the type of operation mainly includes writing, accessing, removing, etc.

Write Cache

First read the write, for example, now has a picture, the address is http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg, then in order to download this image, you can write:

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.openconnecti On (); in = new Bufferedinputstream (Urlconnection.getinputstream (), 8 * 1024x768); out = new Bufferedoutputstream (outputstream , 8 * 1024x768); int B;while ((b = In.read ())! =-1) {out.write (b);} return true;} catch (Final IOException e) {e.printstacktrace ();} finally {if (urlconnection! = null) {Urlconnection.disconnect ();} try {if (out! = null) {Out.close ();} if (in = null) {In.close ();}} catch (Final IOException e) {e.printstacktrace ();}} return false;} 
This code is very basic, I believe everyone can understand, is to access the urlstring in the incoming URL, and write to the local through OutputStream. With this method, we can use Disklrucache to write, and the write operation is done by using the Disklrucache.editor class. Similarly, this class is not new and needs to call Disklrucache's edit () method to get the instance, as shown in the interface below:
Public Editor edit (String key) throws IOException
As you can see, the edit () method receives a parameter key, which will be the file name of the cache file and must correspond to the URL of the image one by one. So how to make the key and the image URL can be one by one corresponding? Use URL directly as key? Inappropriate because the image URL may contain special characters that may not be valid when naming a file. In fact, the simplest way is to encode the URL of the image MD5, the encoded string must be unique, and will only contain characters such as 0-f, fully conform to the naming rules of the file.

Then we'll write a method to encode the string MD5, as shown in the code below:

public string Hashkeyfordisk (string key) {string Cachekey;try {final MessageDigest mdigest = Messagedigest.getinstance (" MD5 "); Mdigest.update (Key.getbytes ()); CacheKey = Bytestohexstring (Mdigest.digest ());} catch (NoSuchAlgorithmException e) {CacheKey = String.valueof (Key.hashcode ());} return CacheKey;}  Private String bytestohexstring (byte[] bytes) {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 ();}
The code is simple, now we just need to call the Hashkeyfordisk () method, and the URL of the image into this method, you can get the corresponding key.

Therefore, it is now possible to write this to get an example of a disklrucache.editor:

String imageUrl = "Http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg"; String key = Hashkeyfordisk (IMAGEURL);D isklrucache.editor Editor = Mdisklrucache.edit (key);
With an instance of Disklrucache.editor, we can call its Newoutputstream () method to create an output stream and then pass it into Downloadurltostream () to download and write to the cache. Note that the Newoutputstream () method receives an index parameter, because the previous specified at the time of setting the Valuecount is 1, so here Index 0 can be. After the write operation is done, we also need to call the commit () method to commit for the write to take effect, and the Abort () method to abort the write.

Therefore, the code for a full write operation is as follows:

New Thread (New Runnable () {@Overridepublic void run () {try {String imageUrl = "http://img.my.csdn.net/uploads/201309/01/ 1378037235_7476.jpg "; String key = Hashkeyfordisk (IMAGEURL);D isklrucache.editor Editor = Mdisklrucache.edit (key); if (Editor! = null) { OutputStream outputstream = editor.newoutputstream (0), if (Downloadurltostream (IMAGEURL, OutputStream)) { Editor.commit ();} else {editor.abort ();}} Mdisklrucache.flush ();} catch (IOException e) {e.printstacktrace ();}}}). Start ();
Since the Downloadurltostream () method is called here to download the image from the network, make sure that the code is executed in the child thread. Note that at the end of the code I also called the Flush () method, which is not required to be called every write, but is indispensable here, and I'll explain it later.

Now that the cache should have been successfully written, we go into the cache directory on the SD card and look at it, as shown in:


As you can see, there is a very long file name, and a journal file, the file name is very long files are naturally cached pictures, because the use of MD5 encoding to be named.

Read cache

After the cache has been written successfully, then we should learn how to read it. The Read method is simpler than writing, mainly by means of the get () method of the Disklrucache, the interface is as follows:

Public synchronized Snapshot get (String key) throws IOException
Obviously, the get () method requires passing in a key to get the corresponding cache data, and this key is undoubtedly the MD5 encoded value of the image URL, so the code to read the cached data can be written like this:
String imageUrl = "Http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg"; String key = Hashkeyfordisk (IMAGEURL);D isklrucache.snapshot Snapshot = Mdisklrucache.get (key);
Strangely enough, what we get here is a Disklrucache.snapshot object, how do we use this object? It is simple to call its getInputStream () method to get the input stream of the cached file. Similarly, the getInputStream () method also needs to pass an index parameter, which is good for passing in 0. With the input stream of the file, it is easy to display the cached image to the interface. So, a complete read cache, and the code that loads the picture into the interface is as follows:
try {String imageUrl = "Http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg"; String key = Hashkeyfordisk (IMAGEURL);D isklrucache.snapshot Snapshot = Mdisklrucache.get (key); if (Snapshot! = null) { InputStream is = snapshot.getinputstream (0); Bitmap Bitmap = Bitmapfactory.decodestream (is); Mimage.setimagebitmap (Bitmap);}} catch (IOException e) {e.printstacktrace ();}

We used the Bitmapfactory Decodestream () method to parse the file stream into a bitmap object, and then set it to ImageView. If you run the program, you will see the following effect:


OK, the picture has been successfully displayed. Note that this is what we load from the local cache, not from the network, so even if your phone is not networked, this picture can still be displayed.

Remove Cache

After learning how to write the cache and read the cache, you have mastered the hardest two operations, and the next step to learn about removing the cache is also very easy for you. The removal of the cache is primarily implemented with the Disklrucache remove () method, as shown in the following interface:

Public synchronized Boolean remove (String key) throws IOException
I'm sure you're pretty familiar with it. The Remove () method requires a key to be passed in, and then deletes the cached image for the key, as shown in the following example code:
try {String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";  String key = Hashkeyfordisk (IMAGEURL);  Mdisklrucache.remove (key);} catch (IOException e) {e.printstacktrace ();}
The usage is simple, but you know, this method should not be used to call it often. Because you don't have to worry about having too much cache data to take up more space on your SD card, Disklrucache automatically deletes extra caches based on the maximum cache value we set when we call the open () method. You should call the Remove () method to remove the cache only if you are sure that the cache content for a key has expired and you need to get the latest data from the network.

Other APIs

In addition to the write cache, read cache, and remove cache, Disklrucache also provides some of the more commonly used APIs that we will simply learn.

1. Size ()

This method returns the total number of bytes for all cached data under the current cache path, in bytes, which can be computed by calling this method if the total size of the current cached data needs to be displayed on the interface in the application. For example, NetEase news has such a feature, as shown in:


2.flush ()

This method synchronizes the in-memory operation records to the log file (that is, the journal file). This approach is very important because the premise of Disklrucache is to rely on the content in the journal file. I have called this method before in explaining the write cache operation, but in fact not every write cache to call the Flush () method, frequent calls do not bring any benefit, only the extra time to synchronize the journal file is added. The standard practice is to call the flush () method in the activity's OnPause () method.

3.close ()

This method is used to shut down the Disklrucache and is a method corresponding to the open () method. The close () method should be called only in the OnDestroy () method of the activity when it is closed and no longer can invoke any method of caching data in Disklrucache.

4.delete ()

This method is used to delete all the cached data, such as the NetEase News in the manual cleanup cache function, in fact, only need to call the Disklrucache Delete () method can be achieved.

Interpreting journal

As mentioned earlier, the prerequisite for Disklrucache to work properly is to rely on the contents of the journal file, so being able to read the journal file is very important for us to understand how Disklrucache works. So what exactly is the content in the journal file? Let's open and take a look, as shown in:



Because now only one picture is cached, there are not a few lines of logs in Journal, and we do the analysis in a row. The first line is a fixed string "Libcore.io.DiskLruCache", signifying that we are using disklrucache technology. The second line is the Disklrucache version number, which is a constant of 1. The third line is the version number of the application, and the version number we passed in the open () method is what is displayed here. Row four is Valuecount, and this value is also passed in the open () method, typically 1. Line Five is a blank line. The first five elements are also known as the head of the journal file, this part of the content is better understood, but the next part will be a little bit more brain.

Line six starts with a dirty prefix, followed by the key that caches the image. Usually we see that the word dirty doesn't represent a good thing, which means it's a dirty piece of data. Yes, every time we call the Disklrucache edit () method, we write a dirty record to the journal file, indicating that we are preparing to write a cache of data, but we do not know what the result will be. The commit () method is then called to indicate a successful write cache, and a clean record is written to the journal, which means that the dirty data is "cleaned up" and the Abort () method is called to indicate that the write cache failed, and a remove record is written to journal. In other words, each line of dirty key, should have a row corresponding to the clean or remove record, otherwise this data is "dirty", will be automatically deleted.

If you are careful enough, you should also notice that the seventh line of the record, in addition to the clean prefix and key, there is a 152313 behind, what does this mean? In fact, Disklrucache will add the size of the cache data, in bytes, at the end of each row of clean records. 152313 that is the number of bytes of the image we have cached, the conversion is probably 148.74K, and the cache image just as large as shown:


The size () method we learned earlier can fetch the total bytes of all cached data under the current cache path, but it works by adding the bytes of all clean records in the journal file, and then returning it.

In addition to dirty, clean, remove, there is a prefix is read record, this is very simple, whenever we call the Get () method to read a cache of data, the journal file will be written to a read record. Therefore, like NetEase news This kind of picture and the data quantity are very big program, the journal file may have the massive read record.

Then you may worry, if I keep working frequently, I will continue to write data to the journal file, so the journal file will not be more and more large? Don't worry, Disklrucache uses a redundantopcount variable to record the number of user actions, each time a write, read, or remove cache operation, the value of this variable will be added 1, When the value of the variable reaches 2000, it triggers the refactoring of the journal event, which automatically clears up some unnecessary and unnecessary records in the journal, ensuring that the size of the journal file remains within a reasonable range.

Okay, so we're going to sort of disklrucache the usage and the brief working principle. As for the source of Disklrucache is relatively simple, limited to the length of the reason is not here to expand, interested friends can explore their own. In the next article, I will take you through a project in a practical way to more deeply understand the use of disklrucache.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.