Recently, I have adopted a dog for a long time. According to the dog owner, it is just Alaska. Please witness it.
Whether it's Alaska or not, I still have to raise it and name it "egg ".
Continue to talk about technology.
Loading images in listview is always an endless topic.
If an image needs to be downloaded for each item in the listview, we have to consider the out of memory problem caused by loading a large number of images.
A typical practice is to check whether the image is in the cache when downloading the image. If the image is not in the cache, read it from the SD card. If the image is not in the cache, download it from the server, the downloaded image is first placed in the SD card and cached. This can be repeated.
This involves how to design the cache. A common practice is to use the LRU algorithm to cache images. First, set a memory area on the mobile phone to cache images, then we will drop the downloaded image in the form of a key-value pair, so that we can get the corresponding image, and the speed is very fast. You must know that reading images from memory is faster than reading files.
The LRU cache code is as follows:
/*** Image cache Note: The image cache uses the classic LRU algorithm. Each file corresponds to a key and the key is used to locate the cached image. ** note that, all the keys obtained are image URLs and values are drawable types. * to ensure the uniformity of keys, the image URLs are uniformly encrypted using MD5, that is to say, all keys are 32-bit strings ** @ author kyson **/public class imagecache {Private Static final string tag = "imagecache "; // obtain the maximum memory allocated by the system to each application. Each application system allocates 32 mprivate static int maxmemory = (INT) (runtime. getruntime (). maxmemory ()/1024); // allocate 1/8 4 mprivate static int cachesize to lrucache = Maxmemory/8; Private Static imagecache instance; Private Static lrucache <string, bitmap> mlrucache = new lrucache <string, bitmap> (cachesize) {// release upon deletion // public Boolean isrecyclewhenremove = true; @ overrideprotected int sizeof (string key, bitmap value) {// todo auto-generated method stub/return Super. sizeof (Key, value); return value. getbytecount ()/1024;} @ overrideprotected void entryremoved (Bo Olean evicted, string key, bitmap oldvalue, bitmap newvalue) {super. entryremoved (evicted, key, oldvalue, newvalue); log. I ("------", "Maximum system memory:" + maxmemory); If (evicted & null! = Oldvalue &&! Oldvalue. isrecycled () {oldvalue. recycle (); oldvalue = NULL ;}/ *** create an image based on the given key */@ overrideprotected bitmap create (string key) {Bitmap bitmap = NULL; filehandler = new filehandler (using application. getcontext (); file = filehandler. findfilebyname (Key, filehandler. getimagepath (); If (file! = NULL) {bitmap = imageutils. readfiletobitmapwithcompress (file. getabsolutepath (); Return bitmap;} return NULL ;};}; public static imagecache reset instance () {If (instance = NULL) {synchronized (imagecache. class) {instance = new imagecache () ;}} return instance ;}private imagecache () {}/ *** load the image. If no, load the default image ** @ Param resid * @ Param imageview */Public bitmap LoadImage (string imageurlstring) {bitmap bit Map = NULL; If (! Textutils. isempty (imageurlstring) {string imagekey = md5encoder. encoding (imageurlstring); system. out. println ("key:" + imagekey); bitmap = mlrucache. get (imagekey);} If (Bitmap! = NULL &&! Bitmap. isrecycled () {log. I (TAG, "Find the corresponding resource in the cache pool and directly return the existing bitmap resource"); Return bitmap;} else {// default image R. drawable. ic_menu_addlog. I (TAG, "the corresponding resource is not found in the cache pool, and the returned bitmap is null"); return NULL ;}} /*** cached image *** @ Param imagenamestring * file name (excluding path) */Public void cacheimage (Bitmap bitmap, string fileurlstring) {If (fileurlstring = NULL | bitmap = NULL) {log. I (TAG, "parameter input error, filenamestring or bitmap is empty"); return;} If (Bitmap! = NULL) {string imagekey = md5encoder. Encoding (fileurlstring); mlrucache. Put (imagekey, bitmap); log. I (TAG, "cache successful! The cached image URL is: "+ fileurlstring +" corresponding key: "+ imagekey);} elselog. I (TAG," cache failed! Corresponding resource already exists in the cache pool ");}/*** @ Param file */Public void cacheimage (File file, string fileurlstring) {If (file = NULL | fileurlstring = NULL) {return;} // drawable = drawable. bitmap bitmap2 = LoadImage (fileurlstring); If (bitmap2 = NULL) {// drawable. createfromstream (inputstream, null); // cache the files in the folder Bitmap bitmap = imageutils. readfiletobitmapwithcompress (file. getabsolutepath (); cacheimage (bitmap, Fileurlstring);} else {system. Out. println ("cache failed! The corresponding resource already exists in the cache pool ");}}}
When cache is a problem, you can see the following code to solve it:
/*** Image downloader class **/public class imagedownload {Private Static final string tag = "imagedownload"; imagedownloadlistener mlistener = NULL; Private Static int alive_time = 30; // number of core threads Private Static int core_size = 5; // maximum number of tasks Private Static int max_size = 15; private Static arrayblockingqueue <runnable> runnables = new arrayblockingqueue <runnable> (25); Private Static threadfactory factory = executors. defaultt Hreadfactory (); // thread pool Private Static threadpoolexecutor mimagethreadpool; private imagecache mimagecache; private filehandler mfilehandler; private context mcontext; Private Static imagedownload instance; public static imagedownload consumer instance (context) {If (instance = NULL) {synchronized (imagecache. class) {instance = new imagedownload (context) ;}return instance ;}public imagedownload (Context Context) {mcontext = context; mfilehandler = new filehandler (context); mimagethreadpool = getthreadpool (); mimagecache = imagecache. concurrent instance ();} public void cancelalltasks () {}/*** method for obtaining the thread pool, we add the synchronization lock ** @ return */Public threadpoolexecutor getthreadpool () {If (mimagethreadpool = NULL) {synchronized (threadpoolexecutor. class) {If (mimagethreadpool = NULL) {// to download images more smoothly, we use two threads to download images. Mimagethreadpool = new threadpoolexecutor (core_size, max_size, alive_time, timeunit. seconds, runnables, factory, new threadpoolexecutor. discardoldestpolicy () ;}} return mimagethreadpool;}/*** obtain a bitmap from the memory cache ** @ Param key * @ return */Public bitmap getbitmapfrommemcache (string key) {return mimagecache. loadImage (key);}/*** add bitmap to memory cache ** @ Param key * @ Param bitmap */Public void addbitmaptomem Orycache (string key, Bitmap bitmap) {If (getbitmapfrommemcache (key) = NULL & bitmap! = NULL) {mimagecache. cacheimage (bitmap, key) ;}}/*** download */Public void downloadimagebyurl (final string imageurlstring, final imagedownloadlistener listener) {If (imageurlstring = NULL) {log. I (TAG, "downloadimagebyurl imageurlstring is null"); return;} final string suburl = md5encoder. encoding (imageurlstring); Final handler = new handler () {@ overridepublic void handlemessage (Message MSG) {super. Handlemessage (MSG); // callback if (msg. OBJ! = NULL) {listener. imagedownloadfinished (Bitmap) MSG. OBJ, imageurlstring); file = mfilehandler. createemptyfiletodownloaddirectory (suburl); imageutils. writebitmap2file (Bitmap) MSG. OBJ, file); addbitmaptomemorycache (imageurlstring, (Bitmap) MSG. OBJ);} else {log. I (TAG, "Download succeeded, but the image is blank !!!!! ") ;}}; // Export cute (New runnable () {// download file @ overridepublic void run () {Bitmap bitmap = getbitmapformurl (imageurlstring); If (Bitmap! = NULL) {message MSG = handler. obtainmessage (); MSG. OBJ = bitmap; handler. sendmessage (MSG); // Add bitmap to the memory cache }}});} /*** download and return the Image Based on the URL ** @ Param URL * @ return */private bitmap getbitmapformurl (string URL) {Bitmap bitmap = NULL; // initialize the image download filedownload = new filedownload (mcontext); // download the image and return whether the file = filedownload is successful. downloadbyurl (URL); // If the download is successful, find the image in the specified path, cache the image, and load the image if (file! = NULL) {log. I (TAG, "image download successful! Using filedownload "); try {log. I ("wenjuan", "image download to file" + file. getpath (); bitmap = bitmapfactory. decodefile (file. getpath ();} catch (outofmemoryerror ERR) {log. I ("<>", "decodefile"); runtime. getruntime (). GC (); bitmap = NULL ;}} else {log. I (TAG, "image download failed! Download the image again and call the built-in download tool "); bitmap = getbitmapformurlwithhttpurlconnection (URL);} return bitmap ;} /*** file downloader ** @ Param URL * @ return */private bitmap getbitmapformurlwithhttpurlconnection (string URL) {Bitmap bitmap = NULL; httpurlconnection con = NULL; try {URL mimageurl = new URL (URL); con = (httpurlconnection) mimageurl. openconnection (); con. setconnecttimeout (10*1000); con. setreadtimeout (10*1000); Con. setrequestmethod ("get"); con. setdoinput (true); con. setdooutput (true); bitmap = bitmapfactory. decodestream (con. getinputstream ();} catch (filenotfoundexception e) {e. printstacktrace ();} catch (protocolexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} catch (outofmemoryerror ee) {runtime. getruntime (). GC (); bitmap = NULL;} finally {If (con! = NULL) {con. disconnect () ;}} return bitmap;}/*** set listener ** @ Param callback */Public void setimagedownloadfinishlistener (imagedownloadlistener) {This. mlistener = imagedownloadlistener;}/*** encapsulate message passing Parameters Using ** @ author kyson **/class messagedata {public Bitmap bitmap; Public String imageurlstring ;}}
Then, the download is involved.
/*** File Download *** @ author kyson **/public class filedownload {Private Static final int status_ OK = 200; private filehandler mfilehandler; Public filedownload (context) {mfilehandler = new filehandler (context);}/*** download the compressed file ** @ Param urlstring * File URL * @ return */Public Boolean downloadbyurlbygzip (string urlstring, string filename) {Boolean downloadsucceed = false; androidhttpclient httpclient = androidhttpclient. newinstance (null); httpclient. getparams (). setparameter ("Accept-encoding", "gzip"); httppost = new httppost (urlstring); httpresponse response = NULL; try {response = httpclient.exe cute (post ); if (response. getstatusline (). getstatuscode () = status_ OK) {httpentity entity = response. getentity (); file = mfilehandler. createemptyfiletodownloaddirectory (filename); inputstream = androidhttpclient. getungzippedcontent (entity); downloadsucceed = streamutil. writestreamtofile (inputstream, file);} else {system. out. println ("server connection problem") ;}} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {httpclient. close () ;}return downloadsucceed ;} /*** download the file to the download directory ** @ Param urlstring * URL address * @ Param filename * specifies the file name * @ return */Public Boolean downloadbyurl (string urlstring, string filename) {Boolean downloadsucceed = false; androidhttpclient httpclient = androidhttpclient. newinstance (null); // httppost post = new httppost (urlstring); httpget get = new httpget (urlstring); httpresponse response = NULL; try {response = httpclient.exe cute (get ); if (response. getstatusline (). getstatuscode () = status_ OK) {httpentity entity = response. getentity (); file = mfilehandler. createemptyfiletodownloaddirectory (filename); entity. writeto (New fileoutputstream (File); downloadsucceed = true;} else {system. out. println ("File Download: server connection problems") ;}} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {httpclient. close ();} return downloadsucceed;}/*** download and return the file ** @ Param urlstring * @ return */Public file downloadbyurl (string urlstring) {androidhttpclient httpclient = androidhttpclient. newinstance (null); httpget get = new httpget (urlstring); file = NULL; try {httpresponse response = httpclient.exe cute (get); If (response. getstatusline (). getstatuscode () = status_ OK) {httpentity entity = response. getentity (); file = mfilehandler. createemptyfiletodownloaddirectory (md5encoder. encoding (urlstring); entity. writeto (New fileoutputstream (File);} else if (response. getstatusline (). getstatuscode () == 404) {system. out. println ("File Download: The downloaded file does not exist") ;}} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {httpclient. close (); httpclient = NULL;} return file ;}}
The last imageview is used to load
/*** View used to load images */public class autoloadimageview extends imageview {public final int defaultimageid =-1; private context mcontext; private imagecache mimagecache; // Private filehandler; public autoloadimageview (context) {super (context); this. mcontext = context; mimagecache = imagecache. using instance (); // filehandler = new filehandler (mcontext);} public autoloadimageview (context Conte XT, attributeset paramattributeset) {super (context, paramattributeset); this. mcontext = context; mimagecache = imagecache. using instance (); // filehandler = new filehandler (mcontext);} public autoloadimageview (context, attributeset attrs, int defstyle) {super (context, attrs, defstyle); this. mcontext = context; mimagecache = imagecache. using instance (); // filehandler = new filehandler (mcontext );}/* ** Load image * @ Param drawable * image */Public void LoadImage (drawable) {// drawable = mainapplication. getcontext (). getresources ()//. getdrawable (R. drawable. button_focused); this. setimagedrawable (drawable);}/*** load image ** @ Param imageurlstring * image URL */private void LoadImage (final string imageurlstring) {// set tagthis. settag (imageurlstring);/*** call the network interface to request images */imagedownload = new IMA Gedownload (mcontext); imagedownload. downloadimagebyurl (imageurlstring, new imagedownloadlistener () {@ overridepublic void imagedownloadfinished (Bitmap bitmap, string filenamestring) {try {If (mcontext! = NULL & bitmap! = NULL &&! Bitmap. isrecycled () {log. E ("kyson", "autoloadimageview. this "+ autoloadimageview. this); autoloadimageview. this. setimagebitmap (Bitmap);} catch (illegalargumentexception e) {log. I ("wenjuan", "can not draw bitmap because it is recycled") ;}@ overridepublic void imagedownloadfinished (drawable image, string filenamestring ){}});} /*** load image ** @ Param imageurlstring * image URL, * @ Param drawableid default image ID */pub LIC void LoadImage (string imageurlstring, int drawableid) {Bitmap bitmap = getbitmapfromcache (imageurlstring); If (Bitmap! = NULL) {This. setimagebitmap (Bitmap);} else {bitmapfactory. options opts = new bitmapfactory. options (); opts. injustdecodebounds = true; If (this. defaultimageid = drawableid) {bitmapfactory. decoderesource (getresources (), R. drawable. default_image_icon, opts);} else {bitmapfactory. decoderesource (getresources (), drawableid, opts);} opts. insamplesize = computesamplesize (OPTs,-1,480*800); opts. injustdeco Debounds = false; bitmap BMP = NULL; try {BMP = bitmapfactory. decoderesource (getresources (), drawableid, opts); this. setimagedrawable (New bitmapdrawable (BMP);} catch (outofmemoryerror ERR) {If (BMP! = NULL) {BMP. Recycle (); BMP = NULL ;}} if (imageurlstring! = NULL) {// bitmapworkertask bitmaptask = new bitmapworkertask (this); // bitmaptask.exe cute (imageurlstring); this. loadImage (imageurlstring) ;}} public int computesamplesize (bitmapfactory. options options, int minsidelength, int maxnumofpixels) {int initialsize = values (options, minsidelength, maxnumofpixels); int roundedsize; If (initialsize <= 8) {roundedsize = 1; while (roundedsize <I Nitialsize) {roundedsize <= 1 ;}} else {roundedsize = (initialsize + 7)/8*8;} return roundedsize;} Private Static int computeinitialsamplesize (bitmapfactory. options options, int minsidelength, int maxnumofpixels) {double W = options. outwidth; double H = options. outheight; int lowerbound = (maxnumofpixels =-1 )? 1: (INT) math. Ceil (math. SQRT (w * H/maxnumofpixels); int upperbound = (minsidelength =-1 )? 128: (INT) math. min (math. floor (W/minsidelength), math. floor (H/minsidelength); If (upperbound <lowerbound) {// return the larger one when there is no overlapping zone. return lowerbound;} If (maxnumofpixels =-1) & (minsidelength =-1) {return 1;} else if (minsidelength =-1) {return lowerbound;} else {return upperbound;} private bitmap getbitmapfromcache (string URL) {If (textutils. isempt Y (URL) {return NULL;} return mimagecache. loadImage (URL);}/*** use this Loading Method in listview ** @ Param imageurlstring * @ Param drawableid * @ Param POS * // public void LoadImage (string imageurlstring, int drawableid, int POS) {// Bitmap bitmap = getbitmapfromcache (imageurlstring); // If (Bitmap! = NULL) {// This. setimagebitmap (Bitmap); //} else {// If (! Textutils. isempty (imageurlstring) {// string suburl = md5encoder. encoding (imageurlstring); // If (filehandler. isfileexists (suburl) // & filehandler. getfilesize (suburl )! = 0) {// obtain bitmap from the SD card/file = filehandler. findfilebyname (suburl, // filehandler. getimagepath (); // log. I ("wenjuan", // "image from SD file" + file. getabsolutepath (); // bitmap bitmap1 = imageutils //. readfiletobitmapwithcompress (File //. getabsolutepath (); // Add bitmap to the memory cache // If (bitmap1! = NULL) {// This. setimagebitmap (bitmap1); // mimagecache. cacheimage (bitmap1, imageurlstring); //} else {// drawable = NULL; // load the default image first // If (this. defaultimageid = drawableid) {// drawable = mainapplication. getcontext (). getresources ()//. getdrawable (R. drawable. default_image_icon); //} else {// drawable = mainapplication. getcontext (). getresources ()//. getdrawable (drawableid); //} // This. setimagedrawable (drawable); // This. loadImage (imageurlstring); //} @ overrideprotected void ondraw (canvas) {try {super. ondraw (canvas);} catch (exception e ){}}}