[Android] asynchronously loading images-Good idea

Source: Internet
Author: User
Import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. io. outputstream; import java.net. URL; import Java. util. hashmap; import Java. util. stack; import android. app. activity; import android. content. context; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. widget. imagevie W;/*** @ author fed * an asynchronous image loading class written by foreigners. You can change it to any adapter baseadapyer. * ** Remember to add permissions, access the Internet, and write external memory (SD card, etc.) * <uses-Permission Android: Name = "android. permission. internet "/> <uses-Permission Android: Name =" android. permission. write_external_storage "/> */public class imageloader {// The simplest in-memory cache implementation. this shoshould be replaced with // something like softreference or bitmapoptions. inpurgeable (since 1.6) Private hashmap <string, bitmap> cache = new has Hmap <string, bitmap> (); photosqueue = new photosqueue (); // task for the queueprivate class phototoload {Public String URL; Public imageview; Public phototoload (string U, imageview I) {url = u; imageview = I;} private file cachedir; Public imageloader (context) {// make the background thead low priority. this way it will not affect // The UI implements cephotoloaderthread. setpr Iority (thread. norm_priority-1); // find the Dir to save cached imagesif (Android. OS. environment. getexternalstoragestate (). equals (Android. OS. environment. media_mounted) cachedir = new file (Android. OS. environment. getexternalstoragedirectory (), "lazylist"); elsecachedir = context. getcachedir (); If (! Cachedir. exists () cachedir. mkdirs ();} final int stub_id = R. drawable. icon; Public void displayimage (string URL, activity, imageview) {If (cache. containskey (URL) imageview. setimagebitmap (cache. get (URL); else {queuephoto (URL, activity, imageview); imageview. setimageresource (stub_id);} private void queuephoto (string URL, activity, imageview) {// This imageview may be Used for other images before. so there may be // some old tasks in the queue. we need to discard them. photosqueue. clean (imageview); phototoload P = new phototoload (URL, imageview); synchronized (photosqueue. photostoload) {photosqueue. photostoload. push (p); photosqueue. photostoload. policyall ();} // start thread if it's not started yetif (photoloaderthread. getstate () = thread. state. new) photoloaderthread. Start ();} private bitmap getbitmap (string URL) {// I identify images by hashcode. not a perfect solution, good for the // demo. string filename = string. valueof (URL. hashcode (); file F = new file (cachedir, filename); // from SD cachebitmap B = decodefile (f); If (B! = NULL) return B; // from webtry {Bitmap bitmap = NULL; inputstream is = new URL (URL ). openstream (); outputstream OS = new fileoutputstream (f); utils. copystream (is, OS); OS. close (); bitmap = decodefile (f); Return bitmap;} catch (exception ex) {ex. printstacktrace (); return NULL ;}// decodes image and scales it to reduce memory consumptionprivate bitmap decodefile (file F) {try {// decode image sizebitmapfactor Y. options o = new bitmapfactory. options (); O. injustdecodebounds = true; bitmapfactory. decodestream (New fileinputstream (F), null, O); // find the correct scale value. it shoshould be the power of 2. final int required_size = 70; int width_tmp = O. outwidth, height_tmp = O. 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 ++;} // decode with insamplesizebitmapfactory. options O2 = new bitmapfactory. options (); o2.insamplesize = scale; return bitmapfactory. decodestream (New fileinputstream (F), null, O2);} catch (filenotfoundexception e) {} return NULL;} public void stopthread () {photoloaderthread. interrupt ();} // stores list of photos to downloadclass photosqueue {private stack <phototoload> photostoload = new stack <Phototoload> (); // removes all instances of this imageviewpublic void clean (imageview image) {for (Int J = 0; j <photostoload. size ();) {If (photostoload. get (j ). imageview = image) photostoload. remove (j); else ++ J ;}} class photosloader extends thread {@ overridepublic void run () {try {While (true) {// thread waits until there are any images to load in the // queueif (photosqueue. photostoload. size () = 0) synchronized (photosqueue. photostoload) {photosqueue. photostoload. Wait () ;}if (photosqueue. photostoload. Size ()! = 0) {phototoload; synchronized (photosqueue. photostoload) {phototoload = photosqueue. photostoload. pop ();} bitmap BMP = getbitmap (phototoload. URL); cache. put (phototoload. URL, BMP); If (string) phototoload. imageview. gettag ()). equals (phototoload. URL) {bitmapdisplayer BD = new bitmapdisplayer (BMP, phototoload. imageview); Activity A = (activity) phototoload. imageview. getcontext ();. runonuithre AD (BD) ;}} if (thread. interrupted () break;} catch (interruptedexception e) {// allow thread to exit }} photosloader photoloaderthread = new photosloader (); // used to display bitmap in the UI threadclass bitmapdisplayer implements runnable {Bitmap bitmap; imageview; Public bitmapdisplayer (Bitmap B, imageview I) {bitmap = B; imageview = I ;} public void run () {If (Bitmap! = NULL) imageview. setimagebitmap (Bitmap); elseimageview. setimageresource (stub_id) ;}} public void receivache () {// clear memory cachecache. clear (); // clear SD cachefile [] files = cachedir. listfiles (); For (file F: Files) F. delete ();}}

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.