Android Open Source Framework Universal-image-loader full parsing (a)---basic introduction and use

Source: Internet
Author: User

Reprint please indicate this article from Xiaanming's blog (http://blog.csdn.net/xiaanming/article/details/26810303), please respect others ' hard work results, thank you!

Hello everyone! Almost two months did not write the article, the previous period is also in the busy change work, prepare for a written interview what things, now new work to find good, new work oneself is also more satisfied, the only regret is to go to a new city, new environment New Start, I hope that they can adapt to the new environment as soon as possible, Now in preparation for the handover of things, I also have some time, so continue to share the android aspects of things.

Believe that we usually do Android applications, how many will be exposed to the asynchronous loading of images, or loading a lot of pictures of the problem, and loading pictures we often encounter many problems, such as picture of the confusion, oom and other problems, for beginners, these problems will be more difficult to solve, So there are a lot of open-source picture loading framework came into being, more famous is Universal-image-loader, I believe many friends have heard or used this powerful picture loading framework, today this article is the basic introduction and use of this framework, Mainly to help those friends who have not used this framework. This project exists on GitHub above Https://github.com/nostra13/Android-Universal-Image-Loader, we can first look at the characteristics of this open source library

    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

Of course, the features listed above may not be complete, to understand some of the other features can only be slowly discovered through our use, then we will look at the simple use of this open source library

Create a new Android project, download the jar package and add it to the Project Libs directory

Create a new MyApplication to inherit application, and in OnCreate () creates the Imageloader configuration parameter and initializes the code to Imageloader as follows

Package Com.example.uil;    Import Com.nostra13.universalimageloader.core.ImageLoader;  Import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;    Import android.app.Application;    public class MyApplication extends application {        @Override public      void OnCreate () {          super.oncreate ();            Create the default imageloader configuration parameter          imageloaderconfiguration config = imageloaderconfiguration                  . Createdefault ( this);                    Initialize imageloader with configuration.          Imageloader.getinstance (). init (configuration);      }    }  

  

imageloaderconfiguration is the configuration parameter of the picture loader imageloader, using the builder mode, Here is a direct use of the Createdefault () method to create a default imageloaderconfiguration, of course, we can also set their own imageloaderconfiguration, set the following

File Cachedir = storageutils.getcachedirectory (context); imageloaderconfiguration config = new Imageloaderconfiguration.builder (context). memorycacheextraoptions (480, 800          )//default = Device screen dimensions. Diskcacheextraoptions (480, +, compressformat.jpeg, or null)          . Taskexecutor (...)          . Taskexecutorforcachedimages (...) . ThreadPoolSize (3)//default. ThreadPriority (thread.norm_priority-1)//default. Tasksprocessingorder (QUEUEPROCESSINGTYPE.FIFO)//default. Denycacheimagemultiplesizesinmemory (). MemoryCache (New LRUMEMORYC          Ache (2 * 1024x768 * 1024x768)). Memorycachesize (2 * 1024x768 * 1024x768). Memorycachesizepercentage (+)//default . DiskCache (New Unlimiteddisccache (Cachedir))//default. Diskcachesize (* 1024x768). Diskcachef Ilecount (+). Diskcachefilenamegenerator (New Hashcodefilenamegenerator ())//default. Imagedownloader (n EW BASEIMAGEDOWNLOader (context))//default. Imagedecoder (New Baseimagedecoder ())//default. Defaultdisplayimageoptions (   Displayimageoptions.createsimple ())//default. Writedebuglogs (). build ();

  

These are all the options configuration, we do not need each in the project to set their own, generally using Createdefault () created by the imageloaderconfiguration can be used, Then call Imageloader's init () method to pass the Imageloaderconfiguration parameter in, imageloader using singleton mode.

Configuring Android Manifest files

<manifest>      <uses-permission android:name= "Android.permission.INTERNET"/>      <!--Include Next Permission if you want to allow UIL to the cache images on SD card--      <uses-permission android:name= "Android.permis Sion. Write_external_storage "/> ...      <application android:name= "MyApplication" > ...      </application>  </manifest>  

  

Then we can load the picture, first we define the activity's layout file

<?xml version= "1.0" encoding= "Utf-8"?> <framelayout  xmlns:android= "http://schemas.android.com/apk/ Res/android "      android:layout_width=" fill_parent "      android:layout_height=" fill_parent ">        < ImageView          android:layout_gravity= "center"          android:id= "@+id/image"          android:src= "@drawable/ic_empty"          android:layout_width= "wrap_content"          android:layout_height= "wrap_content"/>    </framelayout >  

  

There is only one imageview, very simple, next we will go to load the picture, we will find that Imagelader provides a few image loading methods, mainly these several displayimage (), LoadImage (), Loadimagesync (), Loadimagesync () method is synchronous, android4.0 has a feature, network operation can not be in the main thread, so the Loadimagesync () method we do not use

.

loadimage () Loading pictures

We first use Imageloader's LoadImage () method to load the network picture

Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%                    252520photographer.jpg ";              Imageloader.getinstance (). LoadImage (ImageUrl, New Imageloadinglistener () {@Override                            public void onloadingstarted (String imageuri, view view) {}  @Override public void onloadingfailed (String imageuri, view view, Failreason Failreason)  {} @Override public void Onloadingcomplete (String              Imageuri, view view, Bitmap loadedimage) {mimageview.setimagebitmap (loadedimage);                                } @Override public void onloadingcancelled (String imageuri, view view) {   }          });

 The URL of the incoming picture and the Imageloaderlistener, in the callback method Onloadingcomplete () set Loadedimage to ImageView above the line, If you think the incoming imageloaderlistener is too complicated, we can use the Simpleimageloadinglistener class, which provides an empty implementation of the Imageloaderlistener interface method, using the default adapter mode

Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image);          String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg ";                    Imageloader.getinstance (). LoadImage (ImageUrl, New Simpleimageloadinglistener () {                @Override public              Void Onloadingcomplete (String Imageuri, view view,                      Bitmap loadedimage) {                  super.onloadingcomplete (Imageuri, view, Loadedimage);                  Mimageview.setimagebitmap (loadedimage);              }                        });  

 

If we want to specify the size of the picture what to do, this is good, initialize a ImageSize object, specify the width and height of the picture, the code is as follows

Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image);          String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg ";                    ImageSize mimagesize = new ImageSize (+);                    Imageloader.getinstance (). LoadImage (ImageUrl, Mimagesize, New Simpleimageloadinglistener () {                @Override              public void Onloadingcomplete (String imageuri, view view,                      Bitmap loadedimage) {                  Super.onloadingcomplete ( Imageuri, view, loadedimage);                  Mimageview.setimagebitmap (loadedimage);              }                        });  

Displayimageoptions options = new Displayimageoptions.builder ()          . showimageonloading (r.drawable.ic_stub)// Resource or drawable          . Showimageforemptyuri (r.drawable.ic_empty)//resource or drawable          . Showimageonfail ( R.DRAWABLE.IC_ERROR)//resource or drawable          . Resetviewbeforeloading (FALSE)  //default          . Delaybeforeloading.          Cacheinmemory (FALSE)//default          . Cacheondisk (FALSE)///default          . Preprocessor (...)          . Postprocessor (...)          . Extrafordownloader (...)          . Considerexifparams (FALSE)//default.          Imagescaletype (imagescaletype.in_sample_power_of_2)//default          . Bitmapconfig (Bitmap.Config.ARGB_8888)//default          . Decodingoptions (...)          . Displayer (New Simplebitmapdisplayer ())//default.          Handler (new handler ())//default          . Build ();  

  

We'll make a little change to the code above

final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%          252520photographer.jpg ";                    ImageSize mimagesize = new ImageSize (100, 100);                  Display the configuration of the picture displayimageoptions options = new Displayimageoptions.builder (). Cacheinmemory (True)                    . Cacheondisk (True). Bitmapconfig (Bitmap.Config.RGB_565). build ();                Imageloader.getinstance (). LoadImage (ImageUrl, Mimagesize, Options, new Simpleimageloadinglistener () { @Override public void Onloadingcomplete (String imageuri, view view, Bitmap Loade                  DIMAGE) {Super.onloadingcomplete (Imageuri, view, loadedimage);              Mimageview.setimagebitmap (Loadedimage);  }                        }); 

  

We used displayimageoptions to configure some options for displaying pictures, and here I added the caching of pictures to the file system in memory, so that we don't have to worry about loading pictures from the network every time, isn't it convenient, However, some options in the Displayimageoptions option are not valid for the LoadImage () method, such as showimageonloading, Showimageforemptyuri, etc.

displayimage () Loading pictures

Next we'll take a look at another way to load the Web Image displayimage (), the code is as follows

Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image);          String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg ";                    Displays the configuration of the picture          displayimageoptions options = new Displayimageoptions.builder ()                  . showimageonloading ( r.drawable.ic_stub)                  . Showimageonfail (r.drawable.ic_error).                  Cacheinmemory (True).                  Cacheondisk (True)                  . Bitmapconfig (Bitmap.Config.RGB_565)                  . Build ();                    Imageloader.getinstance (). DisplayImage (ImageUrl, Mimageview, Options);  

  

From the code above, we can see that using displayimage () is much more convenient than using LoadImage (), and there is no need to add imageloadinglistener interfaces, and we do not need to manually set ImageView to display bitmap objects. Directly to the ImageView as a parameter passed to DisplayImage () on the line, the picture shows the configuration options, we added a picture loaded in ImageView above the picture shown above, as well as the image loading error display picture, the effect is as follows, just start to show ic_ Stub picture, if the picture is loaded successfully display picture, loading produces error display Ic_error

This method is convenient to use, and using the DisplayImage () method He will be based on the size of the control and Imagescaletype from the cropped image, we modify the next myapplication, turn on log printing

public class MyApplication extends application {        @Override public      void OnCreate () {          super.oncreate ();            Create a default imageloader configuration parameter          imageloaderconfiguration config = new Imageloaderconfiguration.builder (this)          . Writedebuglogs ()//print log information          . Build ();                              Initialize imageloader with configuration.          Imageloader.getinstance (). init (configuration);      }    }  

 Let's take a look at the log message loaded

The first message tells us to start loading the image, print out the URL of the image and the maximum width and height of the image, the width of the image is the width of the device, of course, if we are clear about the size of the picture, we can also go to set this size, In the imageloaderconfiguration option memorycacheextraoptions (int maximagewidthformemorycache, int Maximageheightformemorycache)

The second message shows that the images we loaded are from the network

The third message shows that the original size of the picture is 682 x 341 after clipping

Fourth display picture added to the memory cache, I did not add to the SD card, so no file cache log

When we load the network pictures, there is often need to display the picture download progress requirements, Universal-image-loader of course, also provides such a function, only in DisplayImage () The Imageloadingprogresslistener interface in the method is OK, the code is as follows

Imageloader.displayimage (IMAGEURL, Mimageview, Options, New Simpleimageloadinglistener (), New Imageloadingprogresslistener () {                            @Override public              void Onprogressupdate (String imageuri, view view, int Current,                      int total) {                                }          });  

  Since the method with the Imageloadingprogresslistener parameter in the DisplayImage () method has a imageloadinglistener parameter, I am here directly new A simpleimageloadinglistener, and then we can get the loading progress of the picture in the callback method Onprogressupdate ().

load pictures from other sources

Use Universal-image-loader frame not only can load network picture, also can load SD card picture, Content provider etc., use is also very simple, just will the picture URL slightly change under the line, below is loading file system picture

Displays the configuration of the picture          displayimageoptions options = new Displayimageoptions.builder ()                  . showimageonloading ( r.drawable.ic_stub)                  . Showimageonfail (r.drawable.ic_error).                  Cacheinmemory (True).                  Cacheondisk (True)                  . Bitmapconfig (Bitmap.Config.RGB_565)                  . Build ();                    Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image);          String ImagePath = "/mnt/sdcard/image.png";          String imageUrl = Scheme.FILE.wrap (ImagePath);      String imageUrl = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg";                    Imageloader.displayimage (IMAGEURL, Mimageview, Options);  

And of course it comes from the Content provider,drawable,assets, and it's simple to use, and we just need to add scheme packages to each source of the image (except for content provider), Then, as the URL of the image is passed into the Imageloader, the Universal-image-loader framework gets the input stream according to the different scheme

The image comes from content provider          String contentprividerurl = "CONTENT://MEDIA/EXTERNAL/AUDIO/ALBUMART/13";                    Image from ASSETS          String assetsurl = Scheme.ASSETS.wrap ("Image.png");                    The image is from          String drawableurl = Scheme.DRAWABLE.wrap ("R.drawable.image");  

  


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

Listview.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 (new Weakmemorycache ()) or does not use a memory cache
    • 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

Today to everyone to share here, have not understand the place in the following message, I will try to answer for everyone, the next article I will continue to analyze the framework more deeply, I hope you continue to pay attention!

Android Open Source Framework Universal-image-loader full parsing (a)---basic introduction and use

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.