Universal-image-loader (Android image cache)

Source: Internet
Author: User

Reprint Please specify http://write.blog.csdn.net/postedit?ref=toolbar

Click to download the required jar file

For details , please dabigatran 284568173 Download PDF yourself

Project Description:

Android The most annoying thing is to get pictures from the network, display, recycling, no matter what part of the problem can be directly OOM . This project may be able to help you. Universal image Loader for Android is designed to enable asynchronous loading, caching and display of Web images, and supports multi-threaded asynchronous onboarding. It originally originated from the Fedor Vlasov project. And since then. After large-scale refactoring and improvement.

Feature enumeration:

    1. Multi-threaded Download pictures. Images can come from the web. File system, project directory assets and drawable medium
    2. Support for any configuration imageloader. such as thread pool, picture downloader, memory cache policy. Hard disk cache policy, picture display options, and other configuration
    3. Supports memory caching of images. 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. Good control of the loading process of the picture. For example, pause the image loading, and then start loading the image again, generally used in Listview,gridview. Pauses loading of pictures while sliding. When you stop sliding, load the picture.
    7. Provides loading of pictures on slower networks

Use procedure:

The default imageloader is created, and all operations are controlled by Imageloader .

This class uses a singleton design pattern, so it is necessary to call the GetInstance () method if you want to get the power of the class.

Before you use Imageloader to display a picture, you first initialize its configuration. Call Imageloaderconfiguration's init () method, and you'll be able to implement various displays.

        Create a default imageloader configuration parameter          imageloaderconfiguration configuration = imageloaderconfiguration                  . Createdefault ( this);          Initialize imageloader with configuration.          


Define your own configuration Imageloader, as you already know, first. You need to use the Imageloaderconfiguration object to initialize the Imageloader. Because Imageloader is a singleton, it is only necessary to initialize the program at the beginning of the procedure. It is recommended that you initialize in the activity's OnCreate () method. Assuming that a imageloader has been initialized, there is no effect in initializing again.

Below we create a setting through Imageloaderconfiguration.builder

File Cachedir =storageutils.getowncachedirectory (This, "Imageloader/cache"); imageloaderconfigurationconfig = new Imageloaderconfiguration. Builder (This). Memorycacheextraoptions (480, +)//maxwidth, max height, which is the maximum length of each cached file saved. threadpools            Ize (3)//Line Cheng the number of loads. ThreadPriority (thread.norm_priority-2). Denycacheimagemultiplesizesinmemory () . memorycache (New Usingfreqlimitedmemorycache * 1024x768)//You can pass your own memory cache implementation/ You can implement it through your own memory cache. Memorycachesize (2 * 1024x768 * 1024x768). Disccachesize (* 1024x768). Disc Cachefilenamegenerator (Newmd5filenamegenerator ())//The URI name to be saved is encrypted with MD5. Tasksprocessingorder (Queueprocessingtyp            E.LIFO). Disccachefilecount (100)//cache number of files. Disccache (new Unlimiteddisccache (Cachedir))//define Cache path yourself . Defaultdisplayimageoptions (Displayimageoptions.createsimple ()). Imagedownloader (New BASEIMAGEDOWNLOader (this,5 *, +))//ConnectTimeout (5 s), ReadTimeout (s) time-out. Writedebuglogs ()//Remove fo R Releaseapp. Build ();//Start building imageloader.getinstance (). init (config);


Get Imageloader

Imageloader Imageloader Imageloader = Imageloader.getinstance ();

Use procedure:

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

Displayimageoptions options = new Displayimageoptions.builder ()          . showimageonloading (r.drawable.ic_stub)            // Picture when loading a picture          . Showimageforemptyuri (R.drawable.ic_empty)         //The default picture when there is no picture resource          . Showimageonfail (r.drawable.ic_ Error)              //loading the picture on failure.          Cacheinmemory (TRUE)                               //Enable memory caching          . Cacheondisk (True)                                 //Enable external memory caching          . Considerexifparams (TRUE)                          //enable EXIF and JPEG image formats          . Displayer (new Roundedbitmapdisplayer)         // Set the display style here is the rounded rectangle          . Build ();


Displayimageoptions The following are all the default configuration parameters according to the requirements to be able to define their own configuration

 
                   private int imageresonloading = 0;                    private int imageresforemptyuri = 0;                    private int imageresonfail = 0;                    Private drawable imageonloading = null;                    Private drawable Imageforemptyuri = null;                    Private drawable imageonfail = null;                    Private Boolean resetviewbeforeloading = false;                    Private Boolean cacheinmemory = false;                    Private Boolean cacheondisk = false;                    Private Imagescaletype imagescaletype = imagescaletype.in_sample_power_of_2;                    Private Options Decodingoptions = new options ();                    private int delaybeforeloading = 0;                    Private Boolean considerexifparams = false;                    Private Object extrafordownloader = null;                    Private bitmapprocessor preprocessor = null;           Private Bitmapprocessor postprocessor = null;         Private Bitmapdisplayer Displayer = Defaultconfigurationfactory.createbitmapdisplayer ();                    Private Handler Handler = null; Private Boolean issyncloading = false;

(2) Image loading listener Here it is possible to set the loading animation or the progress bar or something like this.

Imageloadinglistener Animatefirstlistener = new Animatefirstdisplaylistener ();p rivate static class Animatefirstdisplaylistener extends Simpleimageloadinglistener {        static final list<string> displayedimages = Collections.synchronizedlist (New linkedlist<string> ());         @Override public         void Onloadingcomplete (String imageuri, view view, Bitmap loadedimage) {              if (loadedimage! = null {                  ImageView ImageView = (ImageView) view;                  Boolean firstdisplay =!displayedimages.contains (Imageuri);                  if (firstdisplay) {                       fadeinbitmapdisplayer.animate (ImageView, n);                       Displayedimages.add (Imageuri);}}}        


(3) Simple setup can add images to ImageView.

Imageloader.displayimage (IMAGEURL, ImageView, Options, Animatefirstlistener);

For local images, add "file://" before their absolute address.

The network picture directly writes the path.

Because my this is the newest bag. may be different from the old version number, see some netizens said:

String Imageuri = "Http://site.com/image.png"; Network picture string Imageuri = "File:///mnt/sdcard/image.png"; SD card picture String Imageuri = "CONTENT://MEDIA/EXTERNAL/AUDIO/ALBUMART/13"; Media directory String Imageuri = "Assets://image.png"; Assetsstring Imageuri = "drawable://" + r.drawable.image; //  

Cache cleanup:

The cache cleanup can be based on demand, and the ability to clean up each activity's lifecycle function OnDestroy can also be set individually to allow the user to clean it up.

          @Override public          void OnDestroy () {                    Super.ondestroy ();                    Imageloader.clearmemorycache ();                    Imageloader.cleardiskcache ();          }


Girdview,listview Loading Image:

I believe most people use Gridview,listview to display a large number of images, and when we slide gridview,listview at high speed, we want to stop the loading of the images, and load the picture of the current screen when the Gridview,listview stops sliding. , this framework, of course, also provides this feature, which is also very easy 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

Listview.setonscrolllistener (New Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling));  Gridview.setonscrolllistener (New Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling));

The first parameter is our image loading object Imageloader, the second is to control whether to pause loading the picture during the sliding process, assuming that it is necessary to pause the transmission of true, the third parameter controls the fierce sliding interface when the picture is loaded

OutOfMemoryError:

Although this framework has a very good caching mechanism, effectively avoid the production of oom, in general, the probability of generating oom is relatively small. But there is no guarantee that outofmemoryerror will never happen. This framework makes a simple catch for outofmemoryerror, ensuring that our program encounters Oom without being crash out. But suppose we use this framework often to have oom. What should we do to improve it?

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

Configure Bitmapconfig to Bitmap.Config.RGB_565 in the Displayimageoptions option, and rgb_565 will consume twice times less memory than argb_8888 by default because argb_8888 is used.

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 the above. I believe you have a good understanding of the use of Universal-image-loader framework, 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, so if we want to load a fixed-size image, we need to pass a LoadImage object using the ImageSize () method. 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

Universal-image-loader (Android image cache)

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.