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

Source: Internet
Author: User

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.

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:

[Java] View plaincopy
    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:

[Java] View plaincopy
    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

[Java] View plaincopy
    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.

[Java] View plaincopy
  1. imageloaderconfiguration config = new imageloaderconfiguration
  2. . Builder (context)
  3. . Memorycacheextraoptions (480, + ) //Max width, max height, which is the maximum length of each cache file saved
  4. . Disccacheextraoptions (480, + , compressformat.jpeg, up , null) //Can slow imageloader, use it caref Ully (Better don ' t use it)/set cache details, it's best not to set this
  5. . ThreadPoolSize (3)//Line Cheng Chinega load quantity
  6. . threadpriority (Thread.norm_priority- 2)
  7. . Denycacheimagemultiplesizesinmemory ()
  8. . MemoryCache (new Usingfreqlimitedmemorycache (2 * 1024x768 )) //You can pass your own memory cache I mplementation/you can implement it through your own memory cache
  9. . memorycachesize (2 * 1024x768 * 1024x768)
  10. . disccachesize (* 1024x768 )
  11. . Disccachefilenamegenerator (new Md5filenamegenerator ())//Encrypt the URI name at the time of saving with MD5
  12. . Tasksprocessingorder (Queueprocessingtype.lifo)
  13. . Disccachefilecount //cache number of files
  14. . Disccache (new Unlimiteddisccache (cachedir))//Custom cache path
  15. . Defaultdisplayimageoptions (Displayimageoptions.createsimple ())
  16. . Imagedownloader (new Baseimagedownloader (Context, 5 * , + )) //ConnectTimeout (5 s), R Eadtimeout (s) time-out
  17. . Writedebuglogs () //Remove for release app
  18. . build (); //Start building
  19. //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:

[Java] View plaincopy
    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.

[Java] View plaincopy
    1. protected Imageloader Imageloader = Imageloader.getinstance ();

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

[Java] View plaincopy
  1. Displayimageoptions options;
  2. options = new Displayimageoptions.builder ()
  3. . showimageonloading (R.drawable.ic_launcher) //Set picture to display during download
  4. . Showimageforemptyuri (R.drawable.ic_launcher)//Set picture to display when the image URI is empty or wrong
  5. . Showimageonfail (R.drawable.ic_launcher)//Set picture to be displayed during image loading/decoding error
  6. . Cacheinmemory (True)//Set whether the downloaded picture is slow to exist in memory
  7. . Cacheondisc (True)//Set whether the downloaded picture is slow to exist on the SD card
  8. . Considerexifparams (True)//whether to consider JPEG image EXIF parameters (rotate, flip)
  9. . Imagescaletype (imagescaletype.exactly_stretched)//Set the image to display in how it is encoded
  10. . Bitmapconfig (Bitmap.Config.RGB_565)//Set the decoding type of the picture//
  11. . Decodingoptions (android.graphics.BitmapFactory.Options decodingoptions)//Set the decoding configuration of the picture
  12. . delaybeforeloading (int delayinmillis)//int Delayinmillis Set the delay time before download for you
  13. Set up bitmap before adding a picture to the cache
  14. . Preprocessor (Bitmapprocessor preprocessor)
  15. . resetviewbeforeloading (True)//Set whether the picture is reset before downloading, reset
  16. . Displayer (new Roundedbitmapdisplayer)//Whether set to rounded corners, how many radians
  17. . Displayer (new Fadeinbitmapdisplayer)//Whether the animation time after the picture is loaded and gradually entering
  18. . 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:

[Java] View plaincopy
    1. Imageloader.getinstance (). DisplayImage (ImageUrl, ImageView); //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:

[Java] View plaincopy
    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:

[Java] View plaincopy
  1. Imageloader.displayimage (IMAGEURL, ImageView, Options, new Imageloadinglistener () {
  2. @Override
  3. public void onloadingstarted () {
  4. //Execute when loading is started
  5. }
  6. @Override
  7. public void onloadingfailed (Failreason failreason) {
  8. //Load failed to execute when
  9. }
  10. @Override
  11. public void Onloadingcomplete (Bitmap loadedimage) {
  12. //load is successful when executed
  13. }
  14. @Override
  15. public void onloadingcancelled () {
  16. //load is canceled when executed
  17. }});

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:

[Java] View plaincopy
  1. Imageloader.displayimage (IMAGEURL, ImageView, Options, new Imageloadinglistener () {
  2. @Override
  3. public void onloadingstarted () {
  4. //Execute when loading is started
  5. }
  6. @Override
  7. public void onloadingfailed (Failreason failreason) {
  8. //Load failed to execute when
  9. }
  10. @Override
  11. public void Onloadingcomplete (Bitmap loadedimage) {
  12. //load is successful when executed
  13. }
  14. @Override
  15. public void onloadingcancelled () {
  16. //load is canceled when executed
  17. },new Imageloadingprogresslistener () {
  18. @Override
  19. public void Onprogressupdate (String imageuri, view view, int Current,int. total) {
  20. //Update the ProgressBar progress information here
  21. }
  22. });


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 ();

The following people asked how to load local pictures or something, then put the pro-response to add up, thank you for the shortcomings (when used when only thought to use 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://MEDIA/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.

Android-universal-image-loader the use of the class library for asynchronous loading of pictures

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.