"Go" Universal-image-loader (Android picture cache)

Source: Internet
Author: User

Original Http://write.blog.csdn.net/postedit?ref=toolbar

Project Description:

One of the biggest headaches on Android is getting pictures, displays, and recycling from the web, and it's possible that the project can help you with any problem. Universal Image Loader for Android is designed to enable asynchronous loading, caching and display of Web images, and supports multi-threaded asynchronous load. It was originally derived from the project of Fedor Vlasov, and has since been reconstructed and improved on a large scale.

Feature enumeration:

    1. Multi-threaded download pictures, images can be from the network, file system, project folder assets and drawable medium
    2. Supports arbitrary configuration of imageloader, such as thread pool, picture downloader, memory cache policy, hard disk cache policy, picture display options, and other configuration
    3. Memory cache for image support, file system cache or SD card cache
    4. Support for monitoring the image download process
    5. Bitmap is clipped based on the size of the control (ImageView), reducing bitmap memory consumption
    6. Better control of the loading process of the picture, such as pause picture loading, restart loading pictures, generally used in the Listview,gridview, the sliding process to pause loading pictures, stop the slide when to load the picture
    7. Provides loading of pictures on a slower network

Use procedure:

Create the default Imageloader, and all operations are controlled by Imageloader. This class uses a singleton design pattern, so if you want to get the power of that class, you need to call the GetInstance () method. Before using Imageloader to display a picture, you first initialize its configuration, call Imageloaderconfiguration's init () method, and then you can implement various displays.

1         // to create a default Imageloader configuration  parameter 2         Imageloaderconfiguration configuration = imageloaderconfiguration  3                 . Createdefault (  This );   4         // Initialize imageloader with configuration.   5         

Custom Configuration Imageloader, as you already know, first, you need to initialize Imageloader with the Imageloaderconfiguration object. Since Imageloader is a singleton, it is only necessary to initialize it once at the beginning of the program. It is recommended that you initialize in the activity's OnCreate () method. If a imageloader has already been initialized, initializing again will have no effect. Below we create a setting through Imageloaderconfiguration.builder

1File Cachedir =storageutils.getowncachedirectory ( This, "Imageloader/cache");2Imageloaderconfigurationconfig =Newimageloaderconfiguration3. Builder ( This) 4. Memorycacheextraoptions (480, 800)//maxwidth, max height, which is the maximum length of each cache file saved5. ThreadPoolSize (3)//number of lines Cheng Chinega loaded6. ThreadPriority (Thread.norm_priority-2) 7 . Denycacheimagemultiplesizesinmemory ()8. MemoryCache (NewUsingfreqlimitedmemorycache (1024 * 1024))//you can pass your own memory cache implementation/and you are able to implement9. memorycachesize (2 * 1024 * 1024)   Ten. disccachesize (50 * 1024 * 1024)    One. Disccachefilenamegenerator (Newmd5filenamegenerator ())//encrypt the URI name at the time of saving with MD5 A . Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO) -. Disccachefilecount (100)//number of cached files -. Disccache (NewUnlimiteddisccache (Cachedir))//Custom Cache Path the . Defaultdisplayimageoptions (Displayimageoptions.createsimple ()) -. Imagedownloader (NewBaseimagedownloader ( This, 5 * 1000, 30 * 1000))//ConnectTimeout (5 s), ReadTimeout (s) time-out -. Writedebuglogs ()//Remove for Releaseapp -. build ();//Start building +Imageloader.getinstance (). init (config);

Get Imageloader

1 imageloader imageloader imageloader = Imageloader.getinstance ();

Use procedure:

(1) Whether the image operation participates in the cache and the image effect configuration operation

1Displayimageoptions options =NewDisplayimageoptions.builder ()2. showimageonloading (R.drawable.ic_stub)//picture when loading a picture3. Showimageforemptyuri (R.drawable.ic_empty)//default picture when there is no picture resource4. Showimageonfail (R.drawable.ic_error)//picture when load fails5. Cacheinmemory (true)//Enable memory caching6. Cacheondisk (true)//Enable external memory caching7. Considerexifparams (true)//enable EXIF and JPEG image formats8. Displayer (NewRoundedbitmapdisplayer (20))//set the display style here is the rounded rectangle9. build ();

Displayimageoptions The following are all default configuration parameters can be customized according to the requirements of the configuration

1                    Private intimageresonloading = 0;2                     Private intImageresforemptyuri = 0;3                     Private intImageresonfail = 0;4                     Privatedrawable imageonloading =NULL;5                     Privatedrawable Imageforemptyuri =NULL;6                     Privatedrawable Imageonfail =NULL;7                     Private BooleanResetviewbeforeloading =false;8                     Private BooleanCacheinmemory =false;9                     Private BooleanCacheondisk =false;Ten                     PrivateImagescaletype Imagescaletype =imagescaletype.in_sample_power_of_2; One                     PrivateOptions decodingoptions =NewOptions (); A                     Private intdelaybeforeloading = 0; -                     Private BooleanConsiderexifparams =false; -                     PrivateObject Extrafordownloader =NULL; the                     PrivateBitmapprocessor preprocessor =NULL; -                     PrivateBitmapprocessor postprocessor =NULL; -                     PrivateBitmapdisplayer Displayer =Defaultconfigurationfactory.createbitmapdisplayer (); -                     PrivateHandler Handler =NULL; +                     Private BooleanIssyncloading =false;

(2) Picture loading listener here, you can set the animation or the progress bar at the time of loading and stuff like this.

Imageloadinglistener Animatefirstlistener =NewAnimatefirstdisplaylistener ();Private Static classAnimatefirstdisplaylistenerextendsSimpleimageloadinglistener {Static Finallist<string> displayedimages = Collections.synchronizedlist (NewLinkedlist<string>()); @Override Public voidOnloadingcomplete (String imageuri, view view, Bitmap loadedimage) {if(Loadedimage! =NULL) {ImageView ImageView=(ImageView) view; BooleanFirstdisplay =!Displayedimages.contains (Imageuri); if(Firstdisplay) {fadeinbitmapdisplayer.animate (ImageView,500);                    Displayedimages.add (Imageuri); }              }        }}

(3) Simple setup can add a picture to ImageView

1 imageloader.displayimage (IMAGEURL, ImageView, Options, Animatefirstlistener);

Cache cleanup:

The cache cleanup can be based on demand, and can be ondestroy in the life cycle function of each activity or individually set up to let users clean up themselves.

          @Override          publicvoid  OnDestroy () {                    super. OnDestroy ();                    Imageloader.clearmemorycache ();                    Imageloader.cleardiskcache ();          }

Girdview,listview Loading Pictures:

I believe most people use Gridview,listview to display a lot of pictures, and when we slide Gridview,listview quickly, we want to stop the loading of the image, and load the picture of the current screen when the Gridview,listview stops sliding. , this framework of course also provides this function, it is also very simple to use, it provides pauseonscrolllistener this class to control the Listview,gridview sliding process stop to load the picture, the class uses the proxy mode

1 listview.setonscrolllistener (new  Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling));   2 gridview.setonscrolllistener (new Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling));

The first parameter is our picture loading object Imageloader, the second is to control whether to suspend loading the picture during the sliding process, if need to pause to pass true on the line, the third parameter controls the fierce sliding interface when the picture is loaded

OutOfMemoryError:

Although this framework has a good caching mechanism, effectively avoid the production of oom, the general situation of the probability of generating oom is relatively small, but does not guarantee that outofmemoryerror never happen, this framework for OutOfMemoryError do a simple catch, Make sure our program encounters Oom without being crash, but how do we improve if we use this framework often to get oom?

Reduce the number of threads in the thread pool, configured in Imageloaderconfiguration (. threadpoolsize), recommended configuration 1-5

Configure Bitmapconfig as Bitmap.Config.RGB_565 in the displayimageoptions option, because the default is argb_8888, using rgb_565 consumes twice times less memory than using argb_8888

The memory cache for the configuration picture in Imageloaderconfiguration is MemoryCache (Newweakmemorycache ()) or the memory cache is not used

Set the. Imagescaletype (Imagescaletype.in_sample_int) or Imagescaletype (ImageScaleType.EXACTLY) in the displayimageoptions option.

Through these, I believe that the use of Universal-image-loader framework has been very well understood, we use the framework when possible to use the DisplayImage () method to load the picture, LoadImage () is to callback the picture object to the Imageloadinglistener interface of the Onloadingcomplete () method, we need to manually set to ImageView above, DisplayImage () method, Using the weak references for the ImageView object, it is convenient for the garbage collector to reclaim the ImageView object, and if we want to load a fixed-size picture, the LoadImage () method needs to pass a ImageSize object. The DisplayImage () method is based on the measured value of the ImageView object, or the value set by Android:layout_width and Android:layout_height, or Android:maxwidth and/ Or android:maxheight the set value to crop the picture

"Go" Universal-image-loader (Android picture cache)

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.