Write your own Android images asynchronous load library (ii)

Source: Internet
Author: User

In the first article in the series, "DIY Android Image loading library", I learned to use Referencequeue to implement a memory cache. In this article is mainly about how to download a lot of pictures is how to control threads and queues. In this version of the code, adding semaphores and queues, you can control the order of download tasks, you can control the pause and end.

Code A:imageloader.java

/** * Picture Loading Tool class * * @author Qingtian * @blog http://blog.csdn.net/bingoSpunky * */@SuppressLint ("Handlerleak") public class Im Ageloader {private int flag = 0;public static int flag_finished_init_second_thread = 0x1;private static final int default_ Thread_count = 2;private static final int SUCCESS = 1;private static final int FAILED = 0;//configpublic int Configloadin gimage;//the picture that is being displayed now Idpublic int configfailedimage;//The resource displayed when the download fails idpublic Type configtype = type.lifo;//Queue Dispatch mode private Executorservice threadpool;//thread pool private tasks task;//Management task queue//Picture cache private lrucache<string, bitmap> cache; Private Handler mainhandler;//main thread of Handler, modify viewprivate Handler secondhandler;//private volatile Semaphore secondsemaphore;//semaphore control the number of threads being executed and not executed by the second thread = = number of thread pools public Imageloader () {this (default_thread_count);} Public imageloader (int threadnum) {task = new Tasks (), new Thread () {public void run () {looper.prepare (); SecondHandler = NE W Handler () {public void Handlemessage (Android.os.Message msg) {TRy {secondsemaphore.acquire ();} catch (Interruptedexception e) {e.printstacktrace ();} Threadpool.execute (Task.gettask (Configtype));}; Flag |= flag_finished_init_second_thread;task.msemaphore.release (); Looper.loop ();};}. Start (); MainHandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {Imgbeanholder Holder;switch ( Msg.what) {Case success:holder = (imgbeanholder) Msg.obj;imageview ImageView = Holder.imageview; Bitmap BM = Holder.bitmap; String uri = holder.uri;object tag = Imageview.gettag (); if (holder!=null&&holder.listener! = null) {if (tag! = nul L && tag.tostring (). Equals (URI)) {holder.listener.onSuccess (ImageView, True, BM, URI);} else { Holder.listener.onSuccess (ImageView, False, BM, URI);} LOGUTILS.D ("Load failed loading picture URI:" +holder.uri);} Break;case Failed:holder = (imgbeanholder) msg.obj;if (Holder.listener! = null) {holder.listener.onFailed (); LOGUTILS.D ("Load successfully loaded picture URI:" +holder.uri);} break;}}; ThreadPool = new Threadpoolexecutor (threadnum, ThreadnuM, 0,timeunit.seconds, New linkedblockingdeque<runnable> ()); secondsemaphore = new Semaphore (threadnum); int MaxMemory = (int) runtime.getruntime (). MaxMemory (); cache = new lrucache<string, bitmap> (MAXMEMORY/8) {//Measurement Bitmap The size of @overrideprotected int sizeOf (String key, Bitmap value) {return value.getrowbytes () * Value.getheight ();}};} public void display (ImageView IV, String URI) {display (iv, URI, New Simpleimageloaderlistener ());} public void display (final ImageView IV, final String uri,final Imageloaderlistener Imageloaderlistener) throws runtimeexception {if (Imageloaderlistener = = null) {throw new RuntimeException ("Imageloaderlistener cannot be Empty");}    Iv.settag (URI); Showdefalutimage (iv); Task.addtask (flag, new Runnable () {@Overridepublic void run () {LOGUTILS.D ("Start Load picture uri: "+uri); Bitmap BM = Cache.get (URI), if (BM! = null) {LOGUTILS.D ("Load picture uri in memory cache:" +uri); Sendmessagetomainhandler (SUCCESS, BM, IV, Uri,imageloaderlistener);} else {ImageSize ImageSize = Imageviewutil.getimagevIewwidth (iv); LOGUTILS.D ("Load picture URI via network:" +uri); bm = Bitmaputil.decodesampledbitmapfromresource (Uri,imagesize.width, ImageSize.hei ght);//BM = Bitmaputil.getimagebitmap (URI); if (BM! = null) {Cache.put (URI, BM); Sendmessagetomainhandler (SUCCESS, BM, IV , Uri,imageloaderlistener);} else {Sendmessagetomainhandler (FAILED, BM, IV, Uri,imageloaderlistener);}} Secondsemaphore.release ();}}); Secondhandler.sendemptymessage (0x123);} @SuppressWarnings ("deprecation") private static bitmapdrawable mbitmapdrawable = new bitmapdrawable ();p ublic void Showdefalutimage (ImageView IV) {if (configloadingimage! = 0) {iv.setimageresource (configloadingimage);} Else{iv.setimagedrawable (mbitmapdrawable);}} public void Stop () {task.stop ();} public void Restart () {Task.start ();} public void Cancel () {Task.cancel ();} /** * Send message */private void Sendmessagetomainhandler to Handler of the main thread (int what, Bitmap BM, ImageView iv,string URI, Imageloa Derlistener imageloaderlistener) {Imgbeanholder holder = new Imgbeanholder (); holder.bItmap = Bm;holder.imageview = Iv;holder.uri = Uri;holder.listener = Imageloaderlistener; Message msg = Message.obtain (); msg.what = What;msg.obj = Holder;mainhandler.sendmessage (msg);} public class Imgbeanholder {Bitmap Bitmap;imageview ImageView; String Uri;imageloaderlistener Listener;}}

Code B:tasks.java

public class Tasks {public Boolean starting = True;public enum Type{fifo, lifo}/** * introduces a semaphore with a value of 1 to prevent Mpoolthreadhander from initializing complete */public volatile Semaphore Msemaphore = new Semaphore (0);/** * Task Queue */private linkedlist<runnable> mtasks;public T Asks () {mtasks = new linkedlist<runnable> ();} Public synchronized void AddTask (int flag, Runnable Runnable) {try {//Request semaphore, prevent Mpoolthreadhander to NULLIF (Flag & Image Loader.flag_finished_init_second_thread) = = 0) msemaphore.acquire ();} catch (Interruptedexception e) {e.printstacktrace ();} Mtasks.add (runnable);} Public volatile Semaphore Startingsemaphore = new Semaphore (0);/** * Take out a task */public synchronized Runnable gettask (Type ty PE) {if (!starting) {try {logutils.d ("Wait ()"); Wait ();} catch (Interruptedexception e) {e.printstacktrace ()}} if (type = = Type.fifo) {return Mtasks.removefirst ();} else if (type = = Type.lifo) {return mtasks.removelast ();} return null;} Public synchronized void Start () {if (!starting) {starting = True;this.notify (); Logutils. D ("Start Notify ()");} Public synchronized void Stop () {if (starting) {LOGUTILS.D ("Stop ()"); starting = false;}} /** * Cancel All Tasks */public synchronized void Cancel () {mtasks.clear ();}}


SOURCE download



Write your own Android images asynchronous load library (ii)

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.