Android-universal-image-loader Pictures The use of asynchronous load class libraries

Source: Internet
Author: User
Tags md5 encryption

This image of the asynchronous loading and caching of the class has been used by many developers, is one of the most common open source libraries, the mainstream application, the random anti-compilation of several fire projects, can see its figure.

But some people do not know how to use this library how to configure, the information found on the Internet may be too little for the people just contact, below I will use the process I know the written down, I hope to help myself and others more in-depth understanding of the use and configuration of the library.

The download path on GitHub is: Https://github.com/nostra13/Android-Universal-Image-Loader, download the latest library file, and import it into the project Lib to use.

The Library and the demo local download Link:

First, Introduction


Android-universal-image-loader is an open source UI component program designed to provide a reusable instrument for asynchronous image loading, caching, and display. So, if you need this feature in your program, try it. Because some classes and methods have been encapsulated. We can use them directly. Instead of having to write again. In fact, writing a program in this area is still more troublesome, to consider many aspects of multi-threading, caching, memory overflow and so on. However, you can also refer to this example to write a better program yourself. Here to introduce you:

Second, the characteristics


Multi-threaded image loading
The possibility of wide tuning of Imageloader configuration (size of the thread pool, HTTP options, memory and disc cache, display image, and others)
The image of the possibility in the cache memory and/or device of the file system (or SD card)
You can "listen" during the loading process
option to customize each displayed image call delimited
Widget support
Android 1.5 + Support
Briefly describe the structure of the project: each picture's load and display tasks are run in a separate thread, unless the picture is cached in memory, and the slice is immediately displayed. If the desired picture is cached locally, they will open a separate thread queue. If there is no correct picture in the cache, the task thread is fetched from the thread pool, so there is no obvious obstacle to quickly displaying the cached picture. (the part that others have borrowed from)

Flow chart:

Iii. Methods of Use

This is an open source Android about download display image of the tool class, in this download package inside the jar file for our import project use, the specific use of the package also contains. Here is an example:

1 <uses-permission android:name= "Android.permission.INTERNET"/>  2 <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>

Because it is used, the picture gets to go through the network, and there are cache settings, so these 2 permissions must be there.

Many people want to know how to set up a cached directory, which can be done in the following ways:

1 File cachedir = Storageutils.getowncachedirectory (Getapplicationcontext (), "Imageloader/cache");  

This is the directory where you want the cache file: Imageloader/cache

Later in the Imageloaderconfiguration configuration file, set the

1. Disccache (new Unlimiteddisccache (Cachedir))//Custom cache path  

method to set the image cache path for the app.

Let's start by looking at how to use this image to load the library asynchronously:

One.

First, configure the Imageloaderconfiguration class to implement the global Imageloader implementation.

You can choose to initialize the class in application.

 1 imageloaderconfiguration config = new Imageloaderconfiguration 2. Builder (context) 3. Memorycacheextraoptions (480, +)//Max width, max height, which is the maximum width 4 of each cache file saved. disccacheext Raoptions (480, +, Compressformat.jpeg, $, NULL)//Can slow imageloader, use it carefully (Better don't use it)/set cache details Information, it is best not to set this 5. ThreadPoolSize (3)//Line Cheng Chinega load 6. ThreadPriority (thread.norm_priority-2) 7. Denycacheimag Emultiplesizesinmemory () 8. MemoryCache (New Usingfreqlimitedmemorycache (2 * 1024x768 * 1024x768)//You can pass your own m Emory Cache implementation/You can implement 9 with your own memory cache. Memorycachesize (2 * 1024x768 * 1024x768). Disccachesize (50 * 1024 * 1 024) Disccachefilenamegenerator (New Md5filenamegenerator ())//will save the URI name with MD5 encryption. Tasksprocessingorder ( QUEUEPROCESSINGTYPE.LIFO). Disccachefilecount (100)//number of files cached. Disccache (new Unlimiteddisccache (Cachedir))/ /Custom Cache path. defaultdisplayimageoptions (displayimageoptions.createSimple ()) Imagedownloader (new Baseimagedownloader (Context, 5 *, +))//ConnectTimeout (5 s), Readtim Eout (s) Time out. Writedebuglogs ()//Remove for release app. build ();//Start build//Initialize Imageloa   Der with configuration.

The above configuration to see individual needs to choose, not all are to be configured.

After configuring Imageloaderconfiguration, call the following methods to implement initialization:

1 imageloader.getinstance (). init (config);//Global initialization of this configuration  

Note: the. Disccachefilenamegenerator () method in the Imageloaderconfiguration configuration is how the cached file is named

The method that can be called inside is 1.new md5filenamegenerator ()//using MD5 to encrypt UIL name

2.new hashcodefilenamegenerator ()//use Hashcode to encrypt UIL name

Two.

When using Imageloader for picture loading, we first instantiate the Imageloader, call the following methods to instantiate, in each layout to instantiate and then use.

1 protected Imageloader Imageloader = Imageloader.getinstance ();  

After the display of the pictures of the various formats Displayimageoptions settings:

 1 displayimageoptions options; 2 options = new Displayimageoptions.builder () 3. showimageonloading (R.drawable.ic_launcher)//Set the picture shown during Download 4. Show Imageforemptyuri (R.drawable.ic_launcher)//Set picture URI is empty or wrong when the picture is displayed 5. Showimageonfail (r.drawable.ic_launcher)// Set image loading/decoding error when displaying images 6. Cacheinmemory (TRUE)//Set the downloaded picture is slow to exist in memory 7. Cacheondisc (TRUE)//Set the downloaded picture is slow to exist in SD card 8. Considerexifparams (TRUE)//whether to consider JPEG image exif parameter (rotate, flip) 9. Imagescaletype (imagescaletype.exactly_stretched)// Sets how the image is displayed in encoded form. Bitmapconfig (Bitmap.Config.RGB_565)//Set the decoding type of the picture//one by one. Decodingoptions ( Android.graphics.BitmapFactory.Options decodingoptions)//Set the decoding configuration of the picture//.delaybeforeloading (int delayinmillis)// int Delayinmillis Set the delay time before download for you 13//set the picture before adding the cache, set the bitmap to//.preprocessor (Bitmapprocessor preprocessor) 15. Resetviewbeforeloading (TRUE)//sets whether the picture is reset before downloading, resets the Displayer (new Roundedbitmapdisplayer (20))//Whether it is set to a fillet, and how many radians are 17. Displayer (New Fadeinbitmapdisplayer (100))//Whether the picture is loaded and the animation time is gradually entered. build ();//Build Complete 

Follow the configuration you need to set up, if you do not need to do not configure.

Note:

In the above configuration:

1). Imagescaletype (Imagescaletype imagescaletype) is the way to set how the picture is scaled
Scale type Magescaletype:

Exactly: the target size at which the image will be fully scaled

Exactly_stretched: The picture zooms to the target size completely

In_sample_int: The image will be sampled in multiples of two times

In_sample_power_of_2: The picture will be lowered twice times until the next reduction step to make the image smaller target size

NONE: Picture does not adjust
2). Displayer (Bitmapdisplayer displayer) is the way to set the display of pictures

Display mode Displayer:

Roundedbitmapdisplayer (int roundpixels) to set the fillet picture

Fakebitmapdisplayer () This class didn't do anything.

Fadeinbitmapdisplayer (int durationmillis) time to set the picture fade

Simplebitmapdisplayer () normal display of a picture

Then call as required

1. Purely for loading a picture of the default configuration

Method:

public void DisplayImage (String uri, ImageView ImageView) {}

Specific implementation:

2. Load a picture of a custom configuration

Method:

public void DisplayImage (String uri, ImageView ImageView, displayimageoptions options) {}

Specific implementation:

1 imageloader.getinstance (). DisplayImage (ImageUrl, imageview,options); ImageUrl represents the URL address of the picture, ImageView represents the ImageView control that hosts the picture, and the options represents the Displayimageoptions configuration file  

3. Load monitoring when loading the picture

Method:

public void DisplayImage (String uri, Imageaware imageaware, displayimageoptions Options,imageloadinglistener Listener) {}

Imageloadinglistener is used to monitor the download of images.

Specific implementation:

1 imageloader.displayimage (IMAGEURL, ImageView, Options, new Imageloadinglistener () {   2     @Override   3     public void onloadingstarted () {   4        //starts loading at the time of execution   5     }   6     @Override   7 public     Void Onloadingfailed (Failreason failreason) {         8        //load failed when executed   9     }     @Override   11 Public     void Onloadingcomplete (Bitmap loadedimage) {        ///load successful when executed at     Override     The public void onloadingcancelled () {        //load cancellation when executing the     ]});  

4. Picture loading, with monitoring and loading progress bar case
Call:
public void LoadImage (String uri, ImageSize targetimagesize, displayimageoptions options,
Imageloadinglistener Listener, Imageloadingprogresslistener progresslistener) {}
Specific implementation:

1 imageloader.displayimage (IMAGEURL, ImageView, Options, new Imageloadinglistener () {   2     @Override   3     public void onloadingstarted () {   4        //starts loading at the time of execution   5     }   6     @Override   7 public     Void Onloadingfailed (Failreason failreason) {         8        //load failed when executed   9     }     @Override      11 Public     void Onloadingcomplete (Bitmap loadedimage) {        ///load successful when executed at     Override      public     void onloadingcancelled () {+        //load cancellation when performing the     },new Imageloadingprogresslistener () {       @Override public       void Onprogressupdate (String Imageuri, View view, int current,int total) {       //Update ProgressBar's progress information here]       

Iv. precautions
  1. The 2 permissions mentioned above must be added, otherwise error
  2. Imageloaderconfiguration must be configured and globally initialized for this configuration imageloader.getinstance (). init (config);   Error prompts will also appear
  3.ImageLoader determines the width of the picture according to the height,width of the ImageView.
  4. If you often get oom (what others see, it's necessary to mention it)
   ① Reduce the size of the thread pool in the configuration (. threadpoolsize). Recommended 1-5;
    ② use. Bitmapconfig (Bitmap.config.RGB_565) instead of argb_8888;
   ③ use. Imagescaletype (imagescaletype.in_sample_int) or        try.imagescaletype ( imagescaletype.exactly)
   ④ Avoid using Roundedbitmapdisplayer. He will create a new bitmap object in the argb_8888 format;
   ⑤ use. MemoryCache (New Weakmemorycache ()), do not use. Cacheinmemory ();

Someone asked how to load the local picture or something, and then add the pro's answer, thank you for the shortcomings (at that time only thought of using the network pictures, so also did not consider so much).

1 String imageuri = "Http://site.com/image.png"; From Web  2 string imageuri = "File:///mnt/sdcard/image.png",//from SD card  3 String Imageuri = "content://med IA/EXTERNAL/AUDIO/ALBUMART/13 "; From content provider  4 string Imageuri = "Assets://image.png",//From Assets  5 string Imageuri = "drawable:// "+ r.drawable.image; From Drawables (only images, Non-9patch)  

Roughly speaking here, there may be some places are not welcome to put forward, I hope you can more easily start, use this library.

Reprint Address: http://blog.csdn.net/vipzjyno1/article/details/23206387

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.