Android Local Cache Disklrucache Full Detailed learning example

Source: Internet
Author: User

Mainactivity as follows:
Package Cc.vv;import Java.io.file;import Java.io.inputstream;import java.io.outputstream;import Libcore.io.disklrucache;import Libcore.io.utils;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.widget.imageview;import Android.app.activity;import Android.content.Context; Import Android.graphics.bitmap;import android.graphics.bitmapfactory;/** * Demo Description: * Disklrucache Learning Example * * The Disklrucache is used for local caching. * For example, load a network image when the network is available, and still display the image when the network is unavailable. * The principle is to save the picture locally, and load the picture locally when the network is not available. * In this simple simulation of the process, the steps are as follows: * 1 download pictures from the network and save to Disklrucache * 2 get cached pictures from Disklrucache to display * * * Learn notes: * 1 disklrucache the local cache file path is: */ Sdcard/android/data/<application Package>/cache * This file will also be deleted when the app is uninstalled * 2 general Practice for news apps. From the News list (ListView) Click on a piece of news to jump to the detailed screen. * Pictures and text are generally available in the detailed screen. You can use the same key to save your pictures and text under a different cache folder. * When browsing this news when the network is broken, the corresponding pictures and text can be taken out according to the key. * 3 In the example, the associated APIs for Disklrucache are used. Briefly defragment the remaining important APIs here: * 3.1 Remove (String key) deletes a cached object. * 3.2 size () Gets the total amount of cache under the cache path. This is common. Many apps prompt for how many caches are currently available. * 3.3 Flush () the In-memorySynchronization of records to a log file (that is, the journal file) * Typically calls this method in activity's OnPause (). * 3.4 Close () closes Disklrucache. This method corresponds to the open method. * This method is typically called in the activity's ondestory (). * 3.5 Delete () deletes all cached data. * * * Learning Resources: * http://blog.csdn.net/guolin_blog/article/details/28863651 * Thank you very much */public class Mainactiv    ity extends Activity {private ImageView mimageview;    Private Disklrucache Mdisklrucache;    Private Context Mcontext;    The maximum cache value for a picture in Disklrucache.    private int maxsize=20*1024*1024;    Private String mimagepath= "Http://www.baidu.com/img/bdlogo.png";    Private Handler Mhandler;    private final int finish=9527; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); init ();} private void Init () {try {Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {Super.handlemessage (M SG); if (msg.what==finish) {Getdatafromdisklrucache ();}}}; mcontext=this;mimageview= (ImageView) Findviewbyid (R.id.imageview); initDisklrucache ();} catch (Exception e) {//todo:handle exception}}/** * Initialize disklrucache */private void Initdisklrucache () {try {File Cachedir =utils.getdisklrucachedir (Mcontext, "bitmap"), if (!cachedir.exists ()) {cachedir.mkdirs ();} int Versioncode=utils.getappversioncode (mcontext); Mdisklrucache=disklrucache.open (Cachedir, VersionCode, 1, maxSize); Savedatatodisklrucache ();}  catch (Exception e) {///Todo:handle exception}}//writes data to disklrucacheprivate void Savedatatodisklrucache () {New Thread (new Runnable () {@Overridepublic void run () {try {///First step: Gets the corresponding unique key value for the picture to be cached. String key = Utils.getstringbymd5 (Mimagepath);//Second step: Get Disklrucache's Editordisklrucache.editor Editor = Mdisklrucache.edit (key); if (editor!=null) {//Third step: Get Outputstreamoutputstream from editor outputstream= Editor.newoutputstream (0);//Fourth step: Download the network picture and save to Disklrucache in the picture cache Boolean issuccessfull= Utils.getbitmapfromnetworkandsavetodisklrucache (Mimagepath, OutputStream); if (issuccessfull) {editor.commit (); Mhandler.sendemptymessage (FINISH);} Else{editoR.abort ();} Mdisklrucache.flush ();}} catch (Exception e) {}}}). Start ();} Read data from Disklrucache private void Getdatafromdisklrucache () {try {//First step: Gets the corresponding unique key value for the cached picture. String key = Utils.getstringbymd5 (Mimagepath);//Second step: obtain its corresponding snapshotdisklrucache.snapshot based on key snapshot= Mdisklrucache.get (key); if (snapshot!=null) {//Third step: Get from snapshot to Inputstreaminputstream inputstream= Snapshot.getinputstream (0); Bitmap Bitmap=bitmapfactory.decodestream (InputStream); Mimageview.setimagebitmap (Bitmap);}} catch (Exception e) {}}}

Utils as follows:

Package Libcore.io;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import java.io.File; Import Java.io.inputstream;import java.io.outputstream;import java.net.httpurlconnection;import Java.net.URL; Import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;import Org.apache.http.httpstatus;import Android.content.context;import Android.content.pm.packageinfo;import Android.content.pm.packagemanager;import Android.content.pm.packagemanager.namenotfoundexception;import Android.os.environment;public class Utils {/** * get Disklrucache Cache folder * Note the second parameter datatype * Disklrucache distinguishes between different types of data with a unique value of type string. * such as Bitmap,object folder. The picture is cached in the bitmap folder. * * Cache Data Storage location: */sdcard/android/data/<application Package>/cache * If the SD card does not exist when the cache storage location: */data/data/<applicati On Package>/cache * */public static File Getdisklrucachedir (context context, string dataType) {string Dirpath; File cachefile = null;if (Environment.MEDIA_MOUNTED.equals (environment.getexteRnalstoragestate ()) | |! Environment.isexternalstorageremovable ()) {Dirpath=context.getexternalcachedir (). GetPath ();} else {dirPath= Context.getcachedir (). GetPath ();} Cachefile=new File (Dirpath+file.separator+datatype); return cachefile;} /** * Get app Current version number * @param context * @return */public static int Getappversioncode (context context) {int Versioncode=1;try { String Packagename=context.getpackagename (); Packagemanager Packagemanager=context.getpackagemanager (); PackageInfo packageinfo=packagemanager.getpackageinfo (packagename, 0); versioncode=packageinfo.versioncode;} catch (Namenotfoundexception e) {e.printstacktrace ();} return versioncode;} /** * Encodes the string in MD5. * For example, the URL is MD5 encoded in the Change sample */public static string GetStringByMD5 (String string) {string md5string = null;try {//Create MD5 Hash MessageDigest messagedigest = messagedigest.getinstance ("MD5"); Messagedigest.update (String.getbytes ()); byte Messagedigestbytearray[] = Messagedigest.digest (); if (Messagedigestbytearray = = NULL | | messagedigestbytearray.leNgth = = 0) {return md5string;} Create hexadecimal Stringstringbuffer hexadecimalstringbuffer = new StringBuffer (); int length = messagedigestbytearray.length;for (int i = 0; i < length; i++) {Hexadecimalstringbuffer.append (integer.tohexstring ( 0xFF & Messagedigestbytearray[i]);} md5string = Hexadecimalstringbuffer.tostring (); return md5string;} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} return md5string;} /** * A cache */public static Boolean getbitmapfromnetworkandsavetodisklrucache (String imageUrl) from the network that is saved to the SD card OutputStream outputstream) {Boolean issuccessfull=false; URL Url=null; HttpURLConnection Httpurlconnection=null; Bufferedoutputstream Bufferedoutputstream=null;inputstream Inputstream=null; Bufferedinputstream bufferedinputstream=null;try {url=new URL (imageUrl); httpurlconnection= (HttpURLConnection) Url.openconnection (); Httpurlconnection.setconnecttimeout (5*1000); Httpurlconnection.setreadtimeout (10*1000); Httpurlconnection.setdoinput (true); HTTPURLCONNECTION.SETDOOUTPUT (TRUE); if (Httpurlconnection.getresponsecode () ==httpstatus.sc_ok) {bufferedoutputstream=new BufferedOutputStream (OutputStream); Inputstream=httpurlconnection.getinputstream (); Bufferedinputstream=new BufferedInputStream ( InputStream); int Len=0;byte [] buffer=new Byte[1024];while ((len=bufferedinputstream.read (buffer))!=-1) { Bufferedoutputstream.write (buffer, 0, Len); Bufferedoutputstream.flush ();} Issuccessfull=true;} else {issuccessfull=false; System.out.println ("Picture request Failed");}}    catch (Exception e) {issuccessfull=false; System.out.println ("e=" +e.tostring ());} Finally{try {if (bufferedoutputstream!=null) {bufferedoutputstream.close ();} if (inputstream!=null) {inputstream.close ();} if (bufferedinputstream!=null) {bufferedinputstream.close ();} if (httpurlconnection!=null) {httpurlconnection.disconnect ();}} catch (Exception e) {System.out.println ("e=" +e.tostring ());}} return issuccessfull;}}

Main.xml as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">    <imageview        android:id=" @+id/imageview "        android:layout_width=" Wrap_content "        android:layout_height= "wrap_content"        android:layout_centerinparent= "true"/></relativelayout >


Android Local Cache Disklrucache Full Detailed learning example

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.