Android Image level three cache policy

Source: Internet
Author: User
<span id="Label3"></p>1. Introduction<p><p></p></p><pre><pre><code>Android缓存原理都是一样,可以自己封装。</code></pre></pre><p><p>Level Three cache:</p></p><pre><pre><code> 1.内存缓存:缓存在内存中,基于LRU(least recently used )算法,机器重启消失。 2.本地缓存。缓存在本地中。一般键值对形式。(url,filepath) 3.网络缓存。从网络加载资源,然后缓存在内存、本地中。</code></pre></pre><p><p>2. Implementation steps</p></p><p><p>2.1 Memory Cache:</p></p><p><p>[java] View Plain Copy<br>public class Memorycacheutils {<br>Private Lrucache<string,bitmap> mmemorycache;<br>Public Memorycacheutils () {<br>Long maxmemory = runtime.getruntime (). maxmemory ()/8;//get 1/8 of the maximum allowable memory of the phone, that is, more than the specified memory, start the Recycle<br>Need to pass in the maximum allowed memory, virtual machine default memory 16M, The real machine is not necessarily the same<br>Mmemorycache=new lrucache<string,bitmap> ((int) Maxmemory) {<br>Used to calculate the size of each entry<br>@Override<br>protected int sizeOf (String key, Bitmap Value) {<br>int byteCount = Value.getbytecount ();<br>Return byteCount;<br>}<br>};<br>}<br>/**</p></p> <ul> <ul> <li> read pictures from memory </li> <li> <p> @param url <br> <em>/<br> public Bitmap getbitmapfrommemory (String Url) {<br>//bitmap bitm AP = Mmemorycache.get (url);//1. Strong Reference Method <br>/</em> 2. Weak reference method <br> Softreference<bitmap> bitmapsoftreference = Mmemorycache.get (url); <br> If (bitmapsoftreference! = Null) {<br> Bitmap Bitmap = Bitmapsoftreference.get (); <br> Return bitmap; <br>} <br> */<br> if (url==null| | "". equals (url)) {<br> return null; <br>} <br> Bitmap Bitmap = mmemorycache.get (url); </p> <pre> <code> return bitmap; </code> </pre> <p>} <br>/** </p> </li> <li> write a picture in memory </li> <li> @param url </li> <li> @param bitmap <br> <em>/<br> public void Setbitmaptomemory (String url, Bitmap Bitmap) {<br>//mmemorycache.put (url, Bitmap),//1. Strong Reference Method <br>/</em> 2. Weak reference method <br> Mmemorycache.put (url, New Softreference<> (bitmap)); <br> */<br> mmemorycache.put (url,bitmap); <br>} <br>} <br> 2.2 Local cache </li> </ul> </ul><p><p>[java] View Plain Copy<br>public class Localcacheutils {<br>private static final String cache_path= environment.getexternalstoragedirectory (). getabsolutepath () + "/my/images";<br>/**</p></p> <ul> <li><li>Read pictures from local</li></li> <li><li><p>@param URL<br>*/<br>Public Bitmap getbitmapfromlocal (String Url) {<br>String filename = null;//the URL of the picture as the file name and MD5 encryption<br>try {<br>FileName = Md5encoder.encode (url); It doesn't matter if you add or don't encrypt<br>File File=new file (cache_path,filename);<br>Bitmap Bitmap = Bitmapfactory.decodestream (new fileinputstream (file));<br>Return bitmap;<br>} catch (Exception E) {<br>E.printstacktrace ();<br>}<br>Return null;<br>}</p><p>/**</p></li></li> <li><li>After getting pictures from the network, save to local cache</li></li> <li><li>@param URL</li></li> <li><li><p>@param bitmap<br>*/<br>public void setbitmaptolocal (String Url,bitmap Bitmap) {<br>try {</p><pre><code> String fileName = MD5Encoder.encode(url);//把图片的url当做文件名,并进行MD5加密 File file=new File(CACHE_PATH,fileName); //通过得到文件的父文件,判断父文件是否存在 File parentFile = file.getParentFile(); if (!parentFile.exists()){ parentFile.mkdirs(); } //把图片保存至本地 bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file)); } catch (Exception e) { e.printStackTrace(); } </code></pre><p>}<br>}<br>2.3 Network Cache</p></li></li> </ul><p><p>[java] View Plain Copy<br>public class Netcacheutils {<br>Private Localcacheutils mlocalcacheutils;<br>Private Memorycacheutils mmemorycacheutils;</p></p><pre><code>Public netcacheutils (localcacheutils localcacheutils, memorycacheutils memorycacheutils) {mLocalCacheUtils = localCa cheutils; Mmemorycacheutils = memorycacheutils; } public netcacheutils () {}/** * Download pictures from the network * @param ivpic Show pictures of ImageView * @param url to download the Picture's network address */public void GE Tbitmapfromnet (ImageView ivpic, String url) {new bitmaptask (). execute (ivpic, url);//start asynctask} public void Getb Itmapfromnet (View ivpic, String url) {new bitmaptask_view (). execute (ivpic, url);//start asynctask} public Bitmap Getb Itmapfromnet (final String url) {//start asynctask return null; }/** * Asynctask is the encapsulation of handler and thread pool * First generic: parameter type * Second generic: update progress generics * Third generic: onpostexecute return result */class bitmaptask Exte NDS asynctask<object, Void, bitmap> {private ImageView ivpic; Private String url; /** * Background time-consuming operation, existing in Sub-thread * @param params * @return */@Override protected Bitmap doinbackground ( object[] Params) {ivpic = (ImAgeview) params[0]; url = (String) params[1]; return Downloadbitmap (url); }/** * Update progress, in the main thread * @param values */@Override protected void onprogressupdate (void[] value S) {super.onprogressupdate (values); }/** * This method is executed after the time-consuming method, in the main thread * @param result */@Override protected void OnPostExecute (Bitmap R Esult) {if (result! = Null) {ivpic.setimagebitmap (result); System.out.println ("cache Pictures from the network ..."); After obtaining the picture from the network, save to local cache mlocalcacheutils.setbitmaptolocal (url, result); Save to Memory Mmemorycacheutils.setbitmaptomemory (url, result); }}}/** * Asynctask is the encapsulation of handler and thread pool * First generic: parameter type * Second generic: update progress of generics * Third generic: onpostexecute return result */@SuppressLi NT ("newapi") class Bitmaptask_view extends asynctask<object, Void, bitmap> {private View ivpic; Private String url; /** * Background time-consuming operation, existing in child threads * @param params * @return */@Override protected Bitmap doinbackground (object[] Params) { Ivpic = (View) params[0]; url = (String) params[1]; return Downloadbitmap (url); }/** * Update progress, in the main thread * @param values */@Override protected void onprogressupdate (void[] value S) {super.onprogressupdate (values); }/** * This method is executed after the time-consuming method, in the main thread * @param result */@Override protected void OnPostExecute (Bitmap R Esult) {if (result! = Null) {//ivpic.setimagebitmap (result); If (Build.VERSION.SDK_INT >= build.version_codes. Jelly_bean) {//android system is greater than or equal to API16, use SetBackground ivpic.setbackground (new Bitmapdra Wable (result)); } else {//android system is less than API16, use SetBackground ivpic.setbackgrounddrawable (new bitmapdr Awable (result)); } System.ouT.println ("cache Pictures from the network ..."); After obtaining the picture from the network, save to local cache mlocalcacheutils.setbitmaptolocal (url, result); Save to Memory Mmemorycacheutils.setbitmaptomemory (url, result); }}}/** * Network download picture * @param URL * @return */public Bitmap downloadbitmap (String url) {httpurlconnection conn = null; Try {conn = (httpurlconnection) new URL (url). openconnection (); Conn.setconnecttimeout (5000); Conn.setreadtimeout (5000); Conn.setrequestmethod ("GET"); int responsecode = Conn.getresponsecode (); if (responsecode = = 200) {//picture compression bitmapfactory.options Options = new Bitmapfactory.options (); Options.insamplesize=2;//wide and high compression for the original options.inpreferredconfig=bitmap.config.argb_4444; Bitmap Bitmap = Bitmapfactory.decodestream (conn.getinputstream (), null,options); Bitmap Bitmap=bitmapfactory.decodestream (conn.getinpuTStream ()); Return bitmap; }} catch (ioexception e) {e.printstacktrace (); }catch (Exception E) {} finally {if (conn!=null) {conn.disconnect (); }} return null; }</code></pre><p><p>}<br>2.4 Externally write a bitmaputils to invoke Them.</p></p><p><p>[java] View Plain Copy<br>public class Mybitmaputils {<br>Private Netcacheutils mnetcacheutils;<br>Private Localcacheutils mlocalcacheutils;<br>Private Memorycacheutils mmemorycacheutils;</p></p><pre><code>Public mybitmaputils () {mmemorycacheutils=new memorycacheutils (); Mlocalcacheutils=new localcacheutils (); Mnetcacheutils=new netcacheutils (mlocalcacheutils,mmemorycacheutils); } public Bitmap Getbitmap (String Url) {Bitmap bitmap=null; Bitmap=mmemorycacheutils.getbitmapfrommemory (url); If (bitmap!=null) {return bitmap; } bitmap = Mlocalcacheutils.getbitmapfromlocal (url); If (bitmap!=null) {mmemorycacheutils.setbitmaptomemory (url,bitmap); Return bitmap; } return bitmap; } public void DisPlay (ImageView ivpic, String url) {Bitmap Bitmap; Memory Cache Bitmap=mmemorycacheutils.getbitmapfrommemory (url); If (bitmap!=null) {ivpic.setimagebitmap (bitmap); LOG.D ("iamgecache", "get pictures from memory ...--->" +url); Return }//local cache bitmap = mlocalcacheutils.getbitmapfromlocal (url); If (bitmap!=null) {ivpic.setimagebitmap (bitmap); LOG.D ("IAMGECACHe "," get pictures from the local .....--> "+url); After obtaining the picture from the local, save to In-memory mmemorycacheutils.setbitmaptomemory (url,bitmap); Return }//network Cache Mnetcacheutils.getbitmapfromnet (ivpic,url); LOG.D ("iamgecache", "get Pictures from the internet .....-->" +url); } @SuppressLint ("newapi") public void DisPlay (View ivpic, String url) {Bitmap Bitmap; Memory Cache Bitmap=mmemorycacheutils.getbitmapfrommemory (url); If (bitmap!=null) {//ivpic.setimagebitmap (bitmap); If (Build.VERSION.SDK_INT >= build.version_codes. Jelly_bean) {//android system is greater than or equal to API16, use SetBackground ivpic.setbackground (new bitmapdrawable (bi tmap)); } else {//android system is less than API16, use SetBackground ivpic.setbackgrounddrawable (new bitmapdrawable (b itmap)); }//ivpic.setbackground (new bitmapdrawable (bitmap)); LOG.D ("iamgecache", "get pictures from memory ...--->" +url); Return }//local Cache bitmap = MlocalcAcheutils.getbitmapfromlocal (url); If (bitmap!=null) {//ivpic.setimagebitmap (bitmap); If (Build.VERSION.SDK_INT >= build.version_codes. Jelly_bean) {//android system is greater than or equal to API16, use SetBackground ivpic.setbackground (new bitmapdrawable (bi tmap)); } else {//android system is less than API16, use SetBackground ivpic.setbackgrounddrawable (new bitmapdrawable (b itmap)); }//ivpic.setbackground (new bitmapdrawable (bitmap)); LOG.D ("iamgecache", "get Pictures from the local .....-->" +url); After obtaining the picture from the local, save to In-memory mmemorycacheutils.setbitmaptomemory (url,bitmap); Return }//network Cache Mnetcacheutils.getbitmapfromnet (ivpic,url); Ivpic.setbackground (new bitmapdrawable (bitmap)); LOG.D ("iamgecache", "get Pictures from the internet ....-->" +url); }</code></pre><p><p>}<br>The benefits of a personal encapsulated network caching framework are easy to modify and self-aware. suitable for some scenarios where the image quality is not so high and requires a cache to reduce network access.</p></p><p><p>Android Image level three cache policy</p></p></span>

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.