It is not difficult to implement a picture cache, it is necessary to have a corresponding cache policy. Here I use the memory-file-Network layer three cache mechanism, where the memory cache includes strong reference cache and soft-reference cache (SoftReference), in fact, the network is not the cache, it is also zoned into the cache hierarchy1. Introduction
Now the inevitable use of Android applications in the image, some images can be changed, need to be pulled from the network every time, this scene in the application of advertising and pure image applications (such as Baidu Mei Pat) more.
Now there is a problem: if every time you start to pull pictures from the network, it will consume a lot of traffic. In the current situation, for non-wifi users, the traffic is still very expensive, a very traffic-consuming application, the number of users of the order must be affected. Of course, I think, to Baidu Mei Pat such an application, must also have its internal image caching strategy. In short, picture caching is important and necessary.
2. How the image is cached
It is not difficult to implement a picture cache, it is necessary to have a corresponding cache policy. Here I use the memory-file-Network layer three cache mechanism, where the memory cache includes strong reference cache and soft reference cache (SoftReference), in fact, the network is not the cache, and here it is also zoned into the cache hierarchy. When you pull a picture from the network based on the URL, look in memory, if not in memory, and then from the cache file, if not in the cache file, and then pull the image from the network through the HTTP request. In a key-value pair (key-value), the image cache key is the hash value of the image URL, and value is bitmap. So, according to this logic, as long as a URL has been downloaded, its picture is cached.
For soft references to objects in Java (SoftReference), if an object has soft references, enough memory space, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches. Using soft references can prevent memory leaks and enhance the robustness of the program.
From the code, take a imagemanager to manage and cache the image, the function interface is public void LoadBitmap (String url, Handler Handler), where the URL is the image address to download, Handler the callback for the successful download of the image, processing the message in handler, and the message contains the picture's information as well as the bitmap object. The Imagememorycache (memory cache), Imagefilecache (file cache), and LRUCache (the most recently unused cache) used in Imagemanager are described in subsequent articles.
3. Code Imagemanager.java
Copy CodeThe code is as follows:
/* Picture Management * Asynchronously gets the picture, calls directly the LoadImage () function, the function itself determines whether to get the picture from the cache or the network load * synchronously, calls the Getbitmap () function, the function itself determines whether to load from the cache or the network * only obtains the picture from the local, Call Getbitmapfromnative () * To load pictures from the network only, call Getbitmapfromhttp () * */public class Imagemanager implements IManager {private FINA L static String TAG = "Imagemanager"; Private Imagememorycache Imagememorycache; Memory cache private Imagefilecache Imagefilecache; File cache//image list being downloaded public static hashmap<string, handler> Ongoingtaskmap = new hashmap<string, handler> () ; Wait for the downloaded image list public static hashmap<string, handler> Waitingtaskmap = new hashmap<string, handler> (); The number of threads that download the picture at the same time final static int max_download_image_thread = 4; Private final Handler Downloadstatushandler = new Handler () {public void Handlemessage (Message msg) {startdownloadnext (); } }; Public Imagemanager () {Imagememorycache = new Imagememorycache (); imagefilecache = new Imagefilecache ();}/** * Get pictures, multithreading The portal */public void LoadBitmap (String url, Handler Handler) {//////////* * * First fetched from the memory cache, taken to the direct load Bitmap BITMAP = getbitmapfromnative (URL); if (bitmap! = null) {LOGGER.D (TAG, "loadbitmap:loaded from native"); Message msg = Message.obtain (); Bundle bundle = new bundle (); bundle.putstring ("url", url); Msg.obj = bitmap; Msg.setdata (bundle); Handler.sendmessage (msg); } else {LOGGER.D (TAG, "Loadbitmap:will Load by Network"); Downloadbmponnewthread (URL, handler);}} /** * NEW Thread Download image */private void Downloadbmponnewthread (final String URL, final Handler Handler) {LOGGER.D (TAG, "Ongoingtas Kmap ' size= "+ ongoingtaskmap.size ()); if (Ongoingtaskmap.size () >= max_download_image_thread) {synchronized (Waitingtaskmap) {waitingtaskmap.put (URL, handler); }} else {synchronized (ongoingtaskmap) {ongoingtaskmap.put (URL, handler);} new Thread () {public void run () {Bitmap b MP = getbitmapfromhttp (URL); Regardless of whether the download is successful, it is removed from the download queue, and the business logic determines whether to re-download//Download the image using the httpclientrequest, which itself has a heavy connection mechanism synchronized (ONGOINGTASKMAP) { Ongoingtaskmap.remove (URL); } if (Downloadstatushandler! = null) {Downloadstatushandler.sendempTymessage (0); } Message msg = Message.obtain (); Msg.obj = BMP; Bundle bundle = new bundle (); bundle.putstring ("url", url); Msg.setdata (bundle); if (handler! = null) {handler.sendmessage (msg);}} }.start (); }}/** * from memory, cache file, load a single Bitmap on the network, regardless of thread problem */public Bitmap getbitmap (String URL) {//Get picture from memory cache Bitmap Bitmap = Imageme Morycache.getbitmapfrommemory (URL); if (bitmap = = null) {///file cache gets bitmap = Imagefilecache.getimagefromfile (URL); if (bitmap! = null) {//Add to memory cache Imagememo Rycache.addbitmaptomemory (URL, bitmap); } else {//Get bitmap = getbitmapfromhttp (URL) from the Network;}} return bitmap; /** * Get Bitmap */public Bitmap getbitmapfromnative (String URL) from memory or cache file {Bitmap Bitmap = null; Bitmap = Imagememoryca Che.getbitmapfrommemory (URL); if (bitmap = = null) {bitmap = Imagefilecache.getimagefromfile (URL); if (bitmap! = null) {//Add to memory cache IMAGEMEMORYCACHE.ADDBI Tmaptomemory (URL, bitmap); }} return bitmap; /** * Download pictures over the network, thread-independent * * Public Bitmap getbitmapfromhttp (String URL) {Bitmap bmp= NULL; try {byte[] tmppicbyte = getimagebytes (URL), if (tmppicbyte! = null) {BMP = Bitmapfactory.decodebytearray (tmppicbyte, 0, Tmppicbyte.length); } tmppicbyte = null; } catch (Exception e) {e.printstacktrace ();} if (BMP! = null) {//Add to File Cache Imagefilecache.savebitmaptofile (BMP, URL);//Tim Add to Memory cache imagememorycache.addbitmaptomemory (URL, BMP); } return BMP; /** * Download the linked picture resource * * @param URL * * @return picture * * Public byte[] getimagebytes (String URL) {byte[] pic = null; if (URL! = Null &&! "". Equals (URL)) {Requester request = Requesterfactory.getrequester (Requester.request_remote, REQUESTERFACTORY.IMPL_HC) ; Execution request Myresponse myresponse = null; Myrequest mmyrequest; Mmyrequest = new Myrequest (); Mmyrequest.seturl (URL); Mmyrequest.addheader (HttpHeader.REQ.ACCEPT_ENCODING, "identity"); InputStream is = null; Bytearrayoutputstream BAOs = null; try {myresponse = Request.execute (mmyrequest); is = Myresponse.getinputstream (). Getimpl (); BAOs = new Bytearrayoutputstr EAM (); Byte[] B =New BYTE[512]; int len = 0; while (len = Is.read (b))! =-1) {baos.write (b, 0, Len); Baos.flush ();} pic = Baos.tobytearray (); LOGGER.D (TAG, "icon bytes.length=" + pic.length); } catch (Exception E3) {e3.printstacktrace (); try {logger.e (TAG, "Download shortcut icon faild and responsecode=" + Myre Sponse.getstatuscode ()); } catch (Exception e4) {E4.printstacktrace ();}} Finally {try {if (is! = null) {Is.close (); is = null;}} catch (Exception E2) {e2.printstacktrace ();} try {if (BAOs ! = null) {baos.close (); baos = null;}} catch (Exception E2) {e2.printstacktrace ();} try {request.close ();} catch (Exception E1) {E1.printstacktrace ()}} } return pic; }/** * Take out the wait Queue first task, start download */private void Startdownloadnext () {synchronized (Waitingtaskmap) {LOGGER.D (TAG, "Begin Start N") Ext "); Iterator iter = Waitingtaskmap.entryset (). Iterator (); while (Iter.hasnext ()) {Map.entry Entry = (map.entry) iter.next (); LOGGER.D (TAG, "Waitingtaskmap isn ' t null,url=" + (String) Entry.getkey ()); if (entry! = null) {Waitingtaskmap.remove (Entry.getkey ()); Downloadbmponnewthread ((String) Entry.getkey (), (Handler) Entry.getvalue ()); } break; }}} public string Startdownloadnext_forunittest () {string urlstring = null; synchronized (WAITINGTASKMAP) {LOGGER.D (TAG , "Begin start Next"); Iterator iter = Waitingtaskmap.entryset (). Iterator (); while (Iter.hasnext ()) {Map.entry Entry = (map.entry) iter.next (); urlstring = (String) entry.getkey (); waitingtaskmap.re Move (Entry.getkey ()); Break }} return urlstring; /** * Picture turns rounded * @param bitmap: Incoming bitmap * @param pixels: The number of rounded corners, the larger the value, the larger the fillet * @return bitmap: Add fillet bitmap */public static BITM AP Toroundcorner (Bitmap Bitmap, int pixels) {if (Bitmap = = null) return null; Bitmap output = Bitmap.createbitmap (Bitmap.getwidth (), Bitmap.getheight (), config.argb_8888); Canvas canvas = new canvas (output); final int color = 0xff424242; Final Paint paint = new paint (); Final rect rect = new Rect (0, 0, bitmap.getwidth (), Bitmap.getheight ()); Final RECTF RECTF = New RECTF (rect); Final float roundpx = pixels; Paint.setantialias (TRUE); Canvas.drawargb (0, 0, 0, 0); Paint.setcolor (color); Canvas.drawroundrect (RECTF, ROUNDPX, ROUNDPX, paint); Paint.setxfermode (New Porterduffxfermode (mode.src_in)); Canvas.drawbitmap (Bitmap, rect, rect, paint); return output; } public byte ManagerID () {return image_id;}}
Three-level caching cache policy (Memory/file/network) for images in Android