Android okhttp with physical storage media cache: Disklrucache (2)

Source: Internet
Author: User
Tags key string



Android okhttp with physical storage media cache: Disklrucache (2)

Based on the Appendix article 8,9, this article combines the Android Okhttp with Disklrucache to combine these two technologies to achieve okhttp-based physical storage media cache Disklrucache.
Illustrated with a complete example. The code of the example to implement such a process: After the code starts, to a imageview inside a network image, first check whether Disklrucache already exists the cache of the picture, if present, then directly reuse the cache, If it does not exist then use Okhttp to load the picture asynchronously from the network, and when okhttp asynchronously loads the network picture successfully, two things should be done:
One, no doubt, to set the image to the target imageview inside. After the code starts, first checks whether the local Disklrucache physical storage media has a specific picture of the cache, if so, then directly reuse, no longer wasting network resources repeatedly loaded.
Second, the data of the picture is written to the Disklrucache cache and used for subsequent caches. This condition is loaded from the network when Disklrucache does not have a specific resource (in this case a picture) cache. I use Okhttp network driver load, when the okhttp load picture successful, on the one hand to set the picture to ImageView, on the other hand to cache the picture to Disklrucache for later use.

Full code:

Package Zhangphil.demo;import Android.content.context;import Android.content.pm.packageinfo;import Android.content.pm.packagemanager;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.environment;import Android.support.v7.app.appcompatactivity;import Android.os.Bundle;import Android.util.log;import Android.widget.imageview;import Java.io.file;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;import OKHTTP3. Call;import OKHTTP3. Okhttpclient;import OKHTTP3. Request;import OKHTTP3. Response;import OKHTTP3.    Callback;import Com.jakewharton.disklrucache.disklrucache;public class Mainactivity extends AppCompatActivity {    Private String TAG = "Zhangphil_tag";    Private String UNIQUENAME = "Zhangphil_cache";    Private Disklrucache Mdisklrucache = null;    Cache size private int disk_cache_max_size = 10 * 1024 * 1024; @Override protected void ONcreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initialize Disklrucache Makedisklrucache ();        Put a ImageView in the layout, put the network request after the picture final ImageView image = (ImageView) Findviewbyid (R.id.imageview);        My blog head String image_url = "Http://avatar.csdn.net/9/7/A/1_zhangphil.jpg";        Bitmap bmp = Readbitmapfromdisklrucache (Image_url);        First check whether Disklrucache has cached specific resources, and if so, reuse them directly.        If not, it is loaded from the network.        if (BMP! = null) {image.setimagebitmap (BMP);        } else {downloadbitmapfromnetwork (image, Image_url); }}//read cache from Disklrucache private Bitmap readbitmapfromdisklrucache (String URL) {disklrucache.snapshot SNA        Pshot = null;            try {//converts the URL into a MD5 string, and then takes this MD5 string as key string key = Urltokey (URL);        SnapShot = Mdisklrucache.get (key);        } catch (Exception e) {e.printstacktrace (); }        if (snapShot! = null) {LOG.D (TAG, "Discovery cache:" + URL);            InputStream is = snapshot.getinputstream (0);            Bitmap Bitmap = Bitmapfactory.decodestream (IS);            LOG.D (TAG, "read bitmap from cache.");        return bitmap;    } else return null; }//write byte bytes to cache disklrucache private void Writetodisklrucache (String URL, byte[] buf) throws Exception {LOG.D        (TAG, url + ": Start write Cache ...");        Disklrucache cache requires a key, I first convert the URL into a MD5 string,//and then use the MD5 string as the key key string key = Urltokey (URL);        Disklrucache.editor Editor = Mdisklrucache.edit (key);        OutputStream os = editor.newoutputstream (0);        Os.write (BUF);        Os.flush ();        Editor.commit ();        Mdisklrucache.flush ();    LOG.D (TAG, url + ": Write Cache complete.");            private void Makedisklrucache () {try {File Cachedir = Getdiskcachedir (this, UNIQUENAME);    if (!cachedir.exists ()) {LOG.D (TAG, "cache directory does not exist, create ...");            Cachedir.mkdirs ();            } else Log.d (TAG, "the cache directory already exists and does not need to be created."); The second parameter I choose the version of the app code.  Disklrucache if the second parameter version is found to be different then destroy the cache//third parameter is 1, in the write cache stream, Newoutputstream (0), 0 is the index, similar to array subscript Mdisklrucache        = Disklrucache.open (Cachedir, Getversioncode (this), 1, disk_cache_max_size);        } catch (Exception e) {e.printstacktrace (); }} private void Downloadbitmapfromnetwork (final ImageView image, final String image_url) {log.d (TAG, "Add from Network        Download image Resources ... @ "+ image_url);        Initialize Okhttpclient final Okhttpclient client = new Okhttpclient ();        Create a okhttpclient request for data for a URL, requesting requests = new Request.builder (). URL (image_url). build ();        Call call = Client.newcall (request);  Request Join Queue Call.enqueue (new Callback () {@Override public void onfailure (called Call, IOException e) {//Handle business logic for request failure here} @Override public voidOnresponse (call call, Response Response) throws IOException {//If the Response response succeeds then continue, otherwise return if (!                Response.issuccessful ()) return;                This example I wrote is to request a picture of the body of the//response is a picture of byte byte[] bytes = response.body (). bytes ();                The image data has been obtained, recorded to write to the disk cache//For performance reasons, here can be placed in the background or in a thread inside processing//simple period, I am here directly write cache.                try {writetodisklrucache (Image_url, bytes);                } catch (Exception e) {e.printstacktrace ();                }//The byte byte is assembled into a picture final Bitmap bmp = Bitmapfactory.decodebytearray (bytes, 0, bytes.length);                    The callback is run on a non-UI main thread,//After the data request succeeds, update runonuithread (new Runnable () {in the main thread)                        @Override public void Run () {//Network picture request succeeded, updated to ImageView of main thread          Image.setimagebitmap (BMP);          }                });    }        });    }/* * When the SD card is present or the SD card is not removable, call the Getexternalcachedir () method to get the cache path, or call the Getcachedir () method to get the cache path. * The former acquires/sdcard/android/data/<application Package>/cache * and the latter acquires/data/data/<application package>/    Cache.        * * * */Public File Getdiskcachedir (context context, string uniqueName) {string cachepath = null; if (Environment.MEDIA_MOUNTED.equals (Environment.getexternalstoragestate ()) | |!        Environment.isexternalstorageremovable ()) {CachePath = Context.getexternalcachedir (). GetPath ();        } else {CachePath = Context.getcachedir (). GetPath ();        } File Dir = new file (CachePath + file.separator + uniqueName);        LOG.D (TAG, "cache directory:" + Dir.getabsolutepath ());    return dir;    }//Version name public static String Getversionname (context context) {return Getpackageinfo (context). Versionname; }//version number public static int Getversioncode (Context context) {return Getpackageinfo (context). Versioncode;        } private static PackageInfo Getpackageinfo (context context) {PackageInfo pi = null;            try {packagemanager pm = Context.getpackagemanager ();            Pi = Pm.getpackageinfo (Context.getpackagename (), packagemanager.get_configurations);        return pi;        } catch (Exception e) {e.printstacktrace ();    } return pi;    } public static string Urltokey (string url) {return getMD5 (URL);    }/* * Pass in a string of strings MSG, returning the Java MD5 encrypted 16 binary string result.         * Result shape: c0e84e870874dd37ed0d164c7986f03a */public static String GetMD5 (String msg) {MessageDigest MD = null;        try {md = messagedigest.getinstance ("MD5");        } catch (NoSuchAlgorithmException e) {e.printstacktrace ();        } md.reset ();        Md.update (Msg.getbytes ());        byte[] bytes = Md.digest ();        String result = ""; For (Byte b:bYtes) {//byte converted to 16 binary result + = String.Format ("%02x", b);    } return result; }}


For network and read-write storage, do not forget to add permissions:

< Create and delete file permissions!--sdcard---    <uses-permission android:name= "android.permission.MOUNT_UNMOUNT_ Filesystems "/>    <!--write data to SDcard permissions--    <uses-permission android:name=" Android.permission.WRITE _external_storage "/>    <uses-permission android:name=" Android.permission.INTERNET "></ Uses-permission>


Appendix Article:
1, "Android third-party asynchronous Network Load Library asynchttpclient internal implementation of the cache policy?" "Link: http://blog.csdn.net/zhangphil/article/details/48595817
2, "Android image loading and caching open source framework: Android Glide" link: http://blog.csdn.net/zhangphil/article/details/45535693
3, "Android Get App version number and version name" Link: http://blog.csdn.net/zhangphil/article/details/43795099
4, "Java LinkedList-based, implementing Android Big Data cache strategy" link: http://blog.csdn.net/zhangphil/article/details/44116885
5, "replace SoftReference cache image with new LRUCache, Android load image asynchronously" link: http://blog.csdn.net/zhangphil/article/details/43667415
6, "Using Android new LRUCache cache image, based on the thread pool loading pictures asynchronously" link: http://blog.csdn.net/zhangphil/article/details/44082287
7, "Java MD5 (String)" Link: http://blog.csdn.net/zhangphil/article/details/44152077
8, "Android OkHttp (1)" Link: http://blog.csdn.net/zhangphil/article/details/51861503
9, "cache Disklrucache on physical storage media on Android two cache" Link: http://blog.csdn.net/zhangphil/article/details/51888974

Android okhttp with physical storage media cache: Disklrucache (2)

Related Article

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.