Write android image asynchronously loaded library by yourself (2)

Source: Internet
Author: User

Write android image asynchronously loaded library by yourself (2)

In the first article in the "Write android image asynchronously loaded library by yourself" series, I learned how to use ReferenceQueue to implement a memory cache. This article mainly introduces how to control the process and queue when downloading many images. In this version of code, you can add semaphores and queues to control the download task sequence, pause, and end.

Code A: ImageLoader. java

 

/*** Image loading tool class ** @ author qingtian * @ blog http://blog.csdn.net/bingoSpunky */@ SuppressLint (HandlerLeak) public class ImageLoader {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 configLoadingImage; // The currently displayed image idpublic int configFailedImage; // The resource idpublic Type configType = Type displayed when the download fails. LIFO; // private ExecutorService threadPool for queue scheduling; // thread pool private Tasks task; // queue for task Management // private LruCache for image Cache
 
  
Cache; private Handler mainHandler; // handler of the main thread, modify viewprivate Handler secondHandler; // private volatile Semaphore secondSemaphore; // semaphores control the number of threads being executed and not completed 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 () {loader. prepare (); secondHandler = new Handler () {public void handleMessage (android. OS. message MS G) {try {secondSemaphore. acquire ();} catch (InterruptedException e) paie.printstacktrace();}threadpool.exe cute (task. getTask (configType) ;};}; flag | = FLAG_FINISHED_INIT_SECOND_THREAD; task. mSemaphore. release (); logoff. loop ();};}. start (); mainHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {ImgBeanHolder holder; switch (msg. what) {case SUCCESS: holder = (ImgBeanHolder) msg. obj; Imag EView imageView = holder. imageView; Bitmap bm = holder. bitmap; String uri = holder. uri; Object tag = imageView. getTag (); if (holder! = Null & holder. listener! = Null) {if (tag! = Null & tag. toString (). equals (uri) {holder. listener. onSuccess (imageView, true, bm, uri);} else {holder. listener. onSuccess (imageView, false, bm, uri);} LogUtils. d (loading failed to load image uri: + holder. uri);} break; case FAILED: holder = (ImgBeanHolder) msg. obj; if (holder. listener! = Null) {holder. listener. onFailed (); LogUtils. d (the image uri is loaded successfully: + holder. uri) ;}break ;}}; threadPool = new ThreadPoolExecutor (threadNum, threadNum, 0, TimeUnit. SECONDS, new parameter blockingdeque
  
   
(); SecondSemaphore = new Semaphore (threadNum); int maxMemory = (int) Runtime. getRuntime (). maxMemory (); cache = new LruCache
   
    
(MaxMemory/8) {// measure the Bitmap size @ 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) {th Row new RuntimeException (imageLoaderListener cannot be blank);} iv. setTag (uri); showDefalutImage (iv); task. addTask (flag, new Runnable () {@ Overridepublic void run () {LogUtils. d (start to load image uri: + uri); Bitmap bm = cache. get (uri); if (bm! = Null) {LogUtils. d (loading image uri: + uri in the memory cache); sendMessageToMainHandler (SUCCESS, bm, iv, uri, imageLoaderListener);} else {ImageSize imageSize = ImageViewUtil. getImageViewWidth (iv); LogUtils. d (attach image uri through network: + uri); bm = BitmapUtil. decodeSampledBitmapFromResource (uri, imageSize. width, imageSize. height); // bm = BitmapUtil. getImageBitmap (uri); if (bm! = Null) {cache. put (uri, bm); sendMessageToMainHandler (SUCCESS, bm, iv, uri, imageLoaderListener);} else {random (FAILED, bm, iv, uri, imageLoaderListener);} secondSemaphore. release () ;}}); secondHandler. sendEmptyMessage (0x123);} @ SuppressWarnings (deprecation) private static BitmapDrawable mBitmapDrawable = new BitmapDrawable (); public void showDefalutImage (ImageView iv) {if (configLoadingIm Age! = 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 to handler of the main thread */private void sendMessageToMainHandler (int what, Bitmap bm, ImageView iv, String uri, ImageLoaderListener 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, prevent mPoolThreadHander from being initialized */public volatile Semaphore mSemaphore = new Semaphore (0);/*** task queue */private volume list
 
  
MTasks; public Tasks () {mTasks = new shortlist
  
   
();} Public synchronized void addTask (int flag, Runnable runnable) {try {// request semaphores to prevent mPoolThreadHander from being nullif (flag & ImageLoader. FLAG_FINISHED_INIT_SECOND_THREAD) = 0) mSemaphore. acquire ();} catch (InterruptedException e) {e. printStackTrace ();} mTasks. add (runnable);} public volatile Semaphore startingSemaphore = new Semaphore (0);/*** retrieve a task */public synchronized Runnable getTask (Type type) {if (! Starting) {try {LogUtils. d (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. optional Y (); LogUtils. d (start using Y () ;}} public synchronized void stop () {if (starting) {LogUtils. d (stop (); starting = false ;}}/*** cancel all tasks */public synchronized void cancel () {mTasks. clear ();}}
  
 

 

 

Related Article

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.