Android-universal-image-loader the use of the asynchronous Load Class library (Hyper-verbose configuration)

Source: Internet
Author: User

Turn notes

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:

<android:name= "Android.permission.INTERNET"/>  <  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:

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

. Disccache (new Unlimiteddisccache (cachedir))//

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.

imageloaderconfiguration config =Newimageloaderconfiguration. Builder (context). Memorycacheextraoptions (480, 800)//Max width, max height, which is the maximum width of each cached file saved. Disccacheextraoptions (480, 75, Compressformat.jpeg,NULL)//Can Slow Imageloader, use it carefully (Better don't use it)/set cache details, it's best not to set this. ThreadPoolSize (3)//number of lines Cheng Chinega loaded. ThreadPriority (Thread.norm_priority-2). Denycacheimagemultiplesizesinmemory (). MemoryCache (NewUsingfreqlimitedmemorycache (2 * 1024 * 1024))//you can pass your own memory cache implementation/and you are able to implement. memorycachesize (2 * 1024 * 1024). Disccachesize (50 * 1024 * 1024). Disccachefilenamegenerator (NewMd5filenamegenerator ())//encrypt the URI name at the time of saving with MD5. Tasksprocessingorder (Queueprocessingtype.lifo). Disccachefilecount (100)//number of cached files. Disccache (NewUnlimiteddisccache (Cachedir))//Custom Cache Path. Defaultdisplayimageoptions (Displayimageoptions.createsimple ()). Imagedownloader (NewBaseimagedownloader (Context, 5 * 1000, 30 * 1000))//ConnectTimeout (5 s), ReadTimeout (s) time-out. Writedebuglogs ()//Remove for release app. build ();//Start building//Initialize imageloader 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:

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.

protected Imageloader Imageloader = Imageloader.getinstance ();  

after the display of the various formats of the picture displayimageoptions Settings for:

displayimageoptions options; Options=NewDisplayimageoptions.builder (). showimageonloading (R.drawable.ic_launcher)//set the picture that the picture displays during the download. Showimageforemptyuri (R.drawable.ic_launcher)//sets the picture to be displayed when the image URI is empty or wrong. Showimageonfail (R.drawable.ic_launcher)//set picture to display when errors are displayed during image load/decode. Cacheinmemory (true)//sets whether the downloaded picture is slow to exist in memory. Cacheondisc (true)//sets whether the downloaded picture is slow to exist on the SD card. Considerexifparams (true)//whether to consider the JPEG image exif parameter (rotate, flip). Imagescaletype (imagescaletype.exactly_stretched)//set how images are displayed in an encoded manner. Bitmapconfig (Bitmap.Config.RGB_565)//set the decoding type of a picture//. Decodingoptions (Android.graphics.BitmapFactory.Options decodingoptions)//set the decoding configuration for a picture//. delaybeforeloading (int delayinmillis)//int Delayinmillis The delay before the download is set for you//Set up bitmap before adding a picture to the cache//. Preprocessor (bitmapprocessor preprocessor). resetviewbeforeloading (true)//set whether the picture is reset before downloading, reset. Displayer (NewRoundedbitmapdisplayer (20))//is set to fillet, how many radians. Displayer (NewFadeinbitmapdisplayer (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 set How the picture is scaled
     Scale TypeMagescaletype:

exactly: The target size at which the image will be scaled down completely

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 a set how pictures are displayed

display ModeDisplayer:

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:

// ImageUrl represents the URL address of the picture, ImageView represents the ImageView control  that hosts the picture

2. Load a picture of a custom configuration

Method:

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

Specific implementation:

// 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:

Imageloader.displayimage (IMAGEURL, ImageView, Options,NewImageloadinglistener () {@Override Public voidonloadingstarted () {//Execute when loading is started} @Override Public voidonloadingfailed (Failreason failreason) {//execution when the load fails} @Override Public voidOnloadingcomplete (Bitmap loadedimage) {//Execute when loading is successful} @Override Public voidonloadingcancelled () {//execute when load is canceled      }}); 

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:

Imageloader.displayimage (IMAGEURL, ImageView, Options,NewImageloadinglistener () {@Override Public voidonloadingstarted () {//Execute when loading is started} @Override Public voidonloadingfailed (Failreason failreason) {//execution when the load fails} @Override Public voidOnloadingcomplete (Bitmap loadedimage) {//Execute when loading is successful} @Override Public voidonloadingcancelled () {//execute when load is canceled},NewImageloadingprogresslistener () {@Override Public voidOnprogressupdate (String Imageuri, view view,intCurrentintTotal ) {           //Update the progress information for ProgressBar here      }      }); 

Iv. Matters of note
1. The 2 permissions mentioned above must be added or an error will occur
The 2.ImageLoaderConfiguration must be configured and globally initialized for this configuration imageloader.getinstance (). init (config); Otherwise, an error message will also appear
3.ImageLoader determines the width and height of the image according to the ImageView Height,width.
4. If you often have oom (others see it, feel that it is necessary to mention)
① reduces the size of the thread pool in the configuration (. threadpoolsize). Recommendation 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 ();

// From Web   // From SD card   // From content provider   // From assets   // From Drawables (only images, Non-9patch)  

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.