Android asynchronous image loading method 1 (2)

Source: Internet
Author: User

Filecache. Java is as follows:

Package CN. loadimages; import Java. io. file; import android. content. context; import android.net. uri; import android. OS. environment; public class filecache {private file filecachedir; Public filecache (context) {If (environment. getexternalstoragestate (). equals (environment. media_mounted) {filecachedir = new file (environment. getexternalstoragedirectory (), "ideallv001");} else {// context. getcachedir (); // Obtain the directory of the cached file filecachedir = context. getcachedir ();} If (! Filecachedir. exists () {filecachedir. mkdirs () ;}} public file getimagefile (string URL) {// string filename = string. valueof (URL. hashcode (); // string filename = urlencoder. encode (URL); Uri URI uri = Uri. parse (URL); string filename = Uri. getlastpathsegment (); file = new file (filecachedir, filename); Return file;} public void clear () {file [] files = filecachedir. listfiles (); If (Files = NULL) {return;} For (File file: Files) {file. delete ();}}}

Memorycache. Java is as follows:

Package CN. loadimages; import Java. lang. ref. softreference; import Java. util. collections; import Java. util. hashmap; import Java. util. iterator; import Java. util. linkedhashmap; import Java. util. map; import Java. util. map. entry; import Java. util. concurrent. concurrenthashmap; import android. graphics. bitmap; import android. util. log; public class memorycache {Private Static final string tag = "XX"; public static has Hmap <string, integer> bitmapssizehashmap; // 1 creates a level-1 cache // Note: collections is used. synchronizedmap changes it to a synchronized map private Map <string, bitmap> hardbitmapcachehashmap = collections. synchronizedmap (New linkedhashmap <string, bitmap> (10, 1.5f, true); // 2 create a private final static concurrenthashmap <string, softreference <bitmap> softbitmapcachehashmap = new concurrenthashmap <string, softreference <bitmap> (20); // Level 1 Total cache allocation size private long allocatedmemorymaxsize = 0; // The used size of the first-level cache private long nowtotalusedmemorysize = 0; Public memorycache () {// use 10% of available heap size setallocatedmemorymaxsize (runtime. getruntime (). maxmemory ()/10); // 85 bitmapssizehashmap = new hashmap <string, integer> ();} public void setallocatedmemorymaxsize (long allocatedmemorymaxsize) {This. allocatedmemorymaxsize = allocatedmemorymaxsize; log. I (TAG, "allocatedmemorymaxsize =" + allocatedmemorymaxsize/1024/1024 + "MB");} public bitmap getbitmapfrommemory (string URL) {try {// 1 search for the image Bitmap bitmap = hardbitmapcachehashmap from the first-level cache. get (URL); If (Bitmap! = NULL) {// now that you want to get this image, the image is recently used // that is, it is the latest object in all objects. // remove the object from the hardbitmapcachehashmap first // insert it to the front of the hardbitmapcachehashmap. remove (URL); hardbitmapcachehashmap. put (URL, bitmap); Return bitmap;} // 2 search for the image from the second-level cache // if the image is not in shardbitmapcache, this may be because the object is too old // and the shardbitmapcache capacity has reached the upper limit, so I saved it to softbitmapcachehashmap // so I tried to get the object system from softbitmapcachehashmap. out. println ("88 get method from softreferenc E. Obtain "); system. out. println ("88 get URL obtained from softreference =" + URL); softreference <bitmap> bitmapreference = softbitmapcachehashmap. get (URL); If (bitmapreference! = NULL) {bitmap BP = bitmapreference. Get (); If (BP! = NULL) {return bp;} else {// softreference has been recycled by GC softbitmapcachehashmap. remove (URL) ;}} return NULL;} catch (nullpointerexception ex) {ex. printstacktrace (); return NULL ;}} public void putbitmaptomemory (string URL, Bitmap bitmap) {try {If (! Hardbitmapcachehashmap. containskey (URL) {nowtotalusedmemorysize + = getbitmapsizeinbytes (bitmap, URL); system. out. println ("88 put method nowtotalusedmemorysize =" + nowtotalusedmemorysize); checkmemorysizestatus (); hardbitmapcachehashmap. put (URL, bitmap) ;}} catch (throwable th) {th. printstacktrace () ;}/// check the usage of the level-1 cache // if the level-1 cache has reached the upper limit, put the last element in the cache into the softbitmapcachehashmap of the second-level cache. // Add it to the first-level cache and delete private void checkmemorysizestatus () {int hardbitmapcachehashmapsize = hardbitmapcachehashmap. size (); int COUNT = 0; system. out. println ("88 checksizestatus method nowtotalusedmemorysize =" + nowtotalusedmemorysize); system. out. println ("88 checksizestatus method in the memorymaxsize =" + allocatedmemorymaxsize); If (nowtotalusedmemorysize> = allocatedmemorymaxsize) {system. out. println ("nowtotalusedmemorysize> = memorymaxsize"); system. out. in the println ("88 checksizestatus method, hardbitmapcachehashmap. size () = "+ hardbitmapcachehashmap. size (); iterator <entry <string, bitmap> iter = hardbitmapcachehashmap. entryset (). iterator (); // least recently accessed item will be the first one iterated while (ITER. hasnext () {count ++; entry <string, bitmap> entry = ITER. next (); If (COUNT = hardbitmapcachehashmapsize) {system. out. println ("88 checksizestatus method COUNT =" + count); system. out. println ("88 checksizestatus method in memorymaxsize =" + allocatedmemorymaxsize); system. out. println ("88 checksizestatus: nowtotalusedmemorysize =" + nowtotalusedmemorysize); nowtotalusedmemorysize-= getbitmapsizeinbytes (entry. getvalue (), entry. getkey (); // 1 place the last element in softbitmapcachehashmap. put (entry. getkey (), new softreference <bitmap> (entry. getvalue (); system. out. println ("88 checksizestatus method put in softreference url =" + entry. getkey (); system. out. println ("88 checksizestatus method put in softreference softbitmapcachehashmap. size () = "+ softbitmapcachehashmap. size (); // 2 Delete the last element ITER. remove (); // 3 Delete the bitmapssizehashmap element from bitmapssizehashmap. remove (entry. getkey (); system. out. println ("88 checksizestatus method after deleting hardbitmapcachehashmap. size () = "+ hardbitmapcachehashmap. size (); system. out. println ("88 checksizestatus method after deletion softbitmapcachehashmap. size () = "+ softbitmapcachehashmap. size (); system. out. println ("nowtotalusedmemorysize =" + nowtotalusedmemorysize); system. out. println ("88 checksizestatus method after deletion memorymaxsize =" + allocatedmemorymaxsize) ;}}if (Region >= allocatedmemorymaxsize) {checkmemorysizestatus () ;}} public void clear () {try {hardbitmapcachehashmap. clear (); softbitmapcachehashmap. clear (); bitmapssizehashmap. clear (); nowtotalusedmemorysize = 0;} catch (nullpointerexception ex) {ex. printstacktrace () ;}// obtain the bitmap size long getbitmapsizeinbytes (Bitmap bitmap, string URL) {If (Bitmap = NULL) {return 0;} int bitmapsize = bitmapssizehashmap. get (URL); Return bitmapsize; // return bitmap. getrowbytes () * bitmap. getheight ();}}

Imageloader. Java is as follows:

Package CN. loadimages; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. io. outputstream; import java.net. httpurlconnection; import java.net. URL; import Java. util. collections; import Java. util. map; import Java. util. weakhashmap; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import android. app. activit Y; import android. content. context; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. widget. imageview; import CN. ideallistview. r; public class imageloader {memorycache = new memorycache (); filecache; private Boolean success = false; private final int required_bitmap_width = 50; private final int required_bitmap_height = 50; private final in T required_bitmap_maxnumofpixels = 200*200; // see the document: // weakhashmap is not synchronized like most collection classes. // you can use collections. synchronizedmap method to construct a synchronized weakhashmap private Map <imageview, string> imageviewsweakhashmap = collections. synchronizedmap (New weakhashmap <imageview, string> (); executorservice; // The default image final int defaultimageid = R. drawable. stub; Public imageloader (context) {filecache = new filecache (Co Ntext); // create a thread pool that can reuse a set of fixed threads and run these threads executorservice = executors in a shared unbounded queue. newfixedthreadpool (5);} // display the network image public void displayimage (string URL, imageview) {// 1 put the imageview and its corresponding URL in imageviewsweakhashmap. put (imageview, URL); // 2 tries to get the image Bitmap bitmap = memorycache from the memory. getbitmapfrommemory (URL); If (Bitmap! = NULL) {imageview. setimagebitmap (Bitmap);} // 3 is not in the memory, else {taskqueueforimages (URL, imageview) is obtained from the SD card and network; imageview. setimageresource (defaultimageid) ;}} private void upload (string URL, imageview) {willloadedimagebean = new willloadedimagebean (URL, imageview); // submit a runnable task for execution, return a future executorservice indicating the task. submit (New loaderimagesrunnable (willloade Dimagebean);} // This thread runs class loaderimagesrunnable implements runnable {willloadedimagebean; loaderimagesrunnable (willloadedimagebean) {This. willloadedimagebean = willloadedimagebean;} @ override public void run () {try {If (isimageviewreused (willloadedimagebean) {return ;} // obtain the corresponding Bitmap Based on the image URL // 1 search for it from sdcard // 2 if it is not in sdcard, It is downloaded from the network, save the image to sdcard. // 3. Save the SDC The Bitmap bitmap = getbitmapbyurl (willloadedimagebean. URL); // 4 Save the image to memorycache. putbitmaptomemory (willloadedimagebean. URL, bitmap); If (isimageviewreused (willloadedimagebean) {return;} // 5 display bitmap in the UI bitmapdisplayerrunnableinuithread bitmapdisplayerrunnable = new vertex (bitmap, willloadedimagebean ); activity activity = (activity) willloadedimagebean. I Mageview. getcontext (); activity. runonuithread (bitmapdisplayerrunnable);} catch (throwable th) {th. printstacktrace () ;}}// obtain the corresponding bitmap private bitmap getbitmapbyurl (string URL) through the URL {// 1 obtain file = filecache from the SD card. getimagefile (URL); Bitmap bitmap = getbitmapfromsdcardfile (File); If (Bitmap! = NULL) {return bitmap;} else {// 2 If the SD card does not exist, bitmap = getbitmapfromnetwork (URL, file) is downloaded from the network and saved to the file of the SD card ); if (Bitmap! = NULL) {return bitmap;} return NULL;} private bitmap getbitmapfromsdcardfile (File file) {If (! Isgetbitmapthumbnail) {try {fileinputstream inputstream = new fileinputstream (File); Bitmap bitmap = bitmapfactory. decodestream (inputstream); inputstream. close (); Return bitmap;} catch (exception e) {e. printstacktrace () ;}} else {try {string filepath = file. getabsolutepath (); int minsidelength = math. min (required_bitmap_height, required_bitmap_width); bitmap BP = utils. getbitmapthumbnail (filepath, minsidelengt H, required_bitmap_maxnumofpixels); Return bp;} catch (exception e) {e. printstacktrace () ;}} return NULL;} // Private bitmap getbitmapfromsdcardfile (File file) {// try {// decode image size // bitmapfactory. options options1 = new bitmapfactory. options (); // options1.injustdecodebounds = true; // fileinputstream stream1 = new fileinputstream (File); // bitmapfactory. decodestream (stream1, null, options1); // st Ream1.close (); ///// find the correct scale value. it shoshould be the power of 2. // final int required_size = 70; // int width_tmp = options1.outwidth, height_tmp = options1.outheight; // int scale = 1; // while (true) {// If (width_tmp/2 <required_size | height_tmp/2 <required_size) // break; // width_tmp/= 2; // height_tmp/= 2; // scale * = 2; //} // decode with insamplesize // bitmapfactory. options options2 = new bi Tmapfactory. options (); // options2.insamplesize = scale; // fileinputstream stream2 = new fileinputstream (File); // Bitmap bitmap = bitmapfactory. decodestream (stream2, null, options2); // stream2.close (); // system. out. println ("xxxxxxxxxxxxxxxxx F. getpath = "+ file. getpath (); // system. out. println ("xxxxxxxxxxxxxxxxx options1.outwidth =" + options1.outwidth); // system. out. println ("xxxxxxxxxxxxxxxxx options1.outh Eight = "+ options1.outheight); // system. out. println ("xxxxxxxxxxxxxxxxx scale =" + scale); // return bitmap; //} catch (filenotfoundexception e) {//} // catch (ioexception e) {// E. printstacktrace (); //} // return NULL; // download the image from the network and save it to sdcard private bitmap getbitmapfromnetwork (string URL, file) {try {Bitmap bitmap = NULL; Url imageurl = new URL (URL); httpurlconnection conn = (httpurlconnection) imageu RL. openconnection (); Conn. setconnecttimeout (30000); Conn. setreadtimeouts (30000); Conn. setinstancefollowredirects (true); inputstream is = Conn. getinputstream (); // Save the memorycache size. bitmapssizehashmap. put (URL, Conn. getcontentlength (); outputstream OS = new fileoutputstream (File); utils. copystream (is, OS); OS. close (); bitmap = getbitmapfromsdcardfile (File); Return bitmap;} catch (throwable ex) {ex. prin Tstacktrace (); If (ex instanceof outofmemoryerror) {memorycache. clear ();} return NULL ;}}// display bitmap class implements runnable {Bitmap bitmap; willloadedimagebean; Public evaluate (Bitmap bitmap, willloadedimagebean) in the UI thread) {This. bitmap = bitmap; this. willloadedimagebean = willloadedimagebean;} public Vo Id run () {If (isimageviewreused (willloadedimagebean) {return;} If (Bitmap! = NULL) {willloadedimagebean. imageview. setimagebitmap (Bitmap);} else {willloadedimagebean. imageview. setimageresource (defaultimageid) ;}}// task for the queue private class willloadedimagebean {Public String URL; Public imageview; Public willloadedimagebean (string URL, imageview) {This. url = URL; this. imageview = imageview;} Boolean isimageviewreused (willloadedimagebean willlo Adedimagebean) {string imageurl = imageviewsweakhashmap. Get (willloadedimagebean. imageview); If (imageurl = NULL |! Imageurl. Equals (willloadedimagebean. url) {return true;} return false;} public void merge AchE () {memorycache. Clear (); filecache. Clear ();}}

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.