Android-Universal-Image-Loader for asynchronous Android Image loading

Source: Internet
Author: User

Android-Universal-Image-Loader for asynchronous Android Image loading
Overview: Project address: https://github.com/nostra13/Android-Universal-Image-Loader UIL (Universal-Image-Loader) asynchronous Image loading, caching, and display. the class that asynchronously loads and caches this image has been used by many developers. It is one of the most common open-source libraries and mainstream applications. It can decompile several popular projects at will, you can see it. Similar class libraries (Picasso), although Picasso has better APIs, lack of customization. The UIL builder can be used for almost all configurations (the most important of which is that Picasso fails to capture and cache large images ).
Features: Multithread image loading (async or sync) Wide custom Wide customization of ImageLoader's configuration (thread executors, downloader, decoder, memory and disk cache, display image options, etc .) define customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc .) image cache Image caching in memory and/or on disk (device's file System or SD card) Listen to Listening loading process (including downloading progress) briefly describe the structure of this project: each image loading and display task runs in an independent thread, unless the image is cached in the memory, the image is displayed immediately. If the image is cached locally, an independent thread queue is enabled. If there is no correct picture in the cache, the task thread will get it from the thread pool. Therefore, there is no obvious obstacle to quickly display the cached picture.


In the source code, both loadImageSync and loadImage are loaded through displayImage. Let's look at the process:
Preparations for installation: maven:

     
  
   com.nostra13.universalimageloader
      universal-image-loader    
  
   1.9.3
  
 
Gradle:
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
Add network and SD card permissions: because the image is obtained through the network and cache settings are available during use, these two permissions must be available.
     
      
  
 
Pre-configure Application or Activity class (before the first usage of ImageLoader)
// Create global configuration and initialize ImageLoader with this config        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)            ...            .build();        ImageLoader.getInstance().init(config);
Acceptable URIs examples
http://site.com/image.png // from Webfile:///mnt/sdcard/image.png // from SD cardfile:///mnt/sdcard/video.mp4 // from SD card (video thumbnail)content://media/external/images/media/13 // from content providercontent://media/external/video/media/13 // from content provider (video thumbnail)assets://image.png // from assetsdrawable:// + R.drawable.img // from drawables (non-9patch images)
NOTE: Use drawable: // only if you really need it! Always consider the native way to load drawables-ImageView. setImageResource (...) instead of using of ImageLoader.
Example
imageLoader.displayImage(imageUri, imageView);imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {    @Override    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {        // Do whatever you want with Bitmap    }});// Load image, decode it to Bitmap and return Bitmap synchronouslyBitmap bmp = imageLoader.loadImageSync(imageUri);// Load image, decode it to Bitmap and return Bitmap to callbackImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this sizeimageLoader.loadImage(imageUri, targetSize, options, new SimpleImageLoadingListener() {    @Override    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {        // Do whatever you want with Bitmap    }});// Load image, decode it to Bitmap and return Bitmap synchronouslyImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this sizeBitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);
You can also use ImageLoadingProgressListenerListen to the progress.
The ImageLoaderConfiguration configuration should be a global object for the Application. You should configure it only once.
// DON't copy this code to your project! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. file cacheDir = StorageUtils. getCacheDirectory (context); ImageLoaderConfiguration config = new ImageLoaderConfiguration. builder (context ). memoryCacheExtraOptions (480,800) // default = device screen dimensions is recommended. diskCacheExtraOptions (480,800, null )//. diskCacheExtraOptions (480,800, null) is recommended ). task Executor (...). taskExecutorForCachedImages (...). threadPoolSize (3) // default recommended 1-5. threadPriority (Thread. NORM_PRIORITY-2) // default. tasksProcessingOrder (QueueProcessingType. FIFO) // default. denyCacheImageMultipleSizesInMemory () // set the memory cache to prohibit multiple sizes of one image from being cached. This is allowed by default.. MemoryCache (new LruMemoryCache (2*1024*1024) // use the strongly referenced cache. However, we recommend that you use UsingFreqLimitedMemoryCache combined with weak and strong references or WeakMemoryCache with weak references. memoryCacheSize (2*1024*1024 ). memoryCacheSizePercentage (13) // default. diskCache (new UnlimitedDiscCache (cacheDir) // default. diskCacheSize (50*1024*1024 ). diskCacheFileCount (100 ). diskCacheFileNameGenerator (new HashCodeFileNameGenerator () // default. imageDownloader (new BaseImageDownloader (context) // default. imageDecoder (new BaseImageDecoder () // default. defaultDisplayImageOptions (DisplayImageOptions. createSimple () // default. writeDebugLogs (). build ();
Sample configuration cache directory
File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), imageloader/Cache);  
. DiskCache (new UnlimitedDiscCache (cacheDir) // customize the cache path
Configure Display Options
// DON't copy this code to your project! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. 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 (0, 1000 ). cacheInMemory (false) // default. cacheOnDisk (false) // default. preProcessor (...). postProcessor (...). extraForDownloader (...). considerExifParams (false) // default. imageScaleType (ImageScaleType. IN_SAMPLE_POWER_OF_2) // default is recommended. imageScaleType (ImageScaleType. EXACTLY) saves memory. bitmapConfig (Bitmap. config. ARGB_8888) // default recommendation. bitmapConfig (Bitmap. config. RGB_565) memory saving. decodingOptions (...). displayer (new SimpleBitmapDisplayer () // default // we recommend that you use RoundedBitmapDisplayer (Displays bitmap with rounded corners) and FadeInBitmapDisplayer (Displays image with fade in animation. handler (new Handler () // default. build ();
In the above Configuration:
1). imageScaleType (ImageScaleType imageScaleType) is used to set the image scaling mode.
Scale type mageScaleType:
EXACTLY: the size of the target image that will be scaled down in proportion.
EXACTLY_STRETCHED: The image is scaled to the target size.
IN_SAMPLE_INT: integer multiple of the image to be sampled twice
IN_SAMPLE_POWER_OF_2: The image will be reduced by 2 times until the next step is reduced to make the image smaller.
NONE: The image is not adjusted.
2). displayer (BitmapDisplayer displayer) is used to set the image display mode.
Display Mode displayer:
RoundedBitmapDisplayer (int roundPixels) Set rounded corner Image
The FakeBitmapDisplayer () class does nothing.
FadeInBitmapDisplayer (int durationMillis) sets the time when the image is gradually displayed.
SimpleBitmapDisplayer () normally displays an image

Notes 1. cache is not enabled by default. You can enable DisplayImageOptions.
// Create default options which will be used for every //  displayImage(...) call if no options will be passed to this methodDisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()        ...        .cacheInMemory(true)        .cacheOnDisk(true)
boolean pauseOnScroll = false; // or true boolean pauseOnFling = true; // or false PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling); listView.setOnScrollListener(listener);

.... Build (); ImageLoaderConfiguration config = new ImageLoaderConfiguration. builder (getApplicationContext ()).... defaultDisplayImageOptions (defaultOptions ).... build (); ImageLoader. getInstance (). init (config); // Do it on Application start
 
// Then later, when you want to display imageImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used
Alternatively, use the following method:
DisplayImageOptions options = new DisplayImageOptions.Builder()        ...        .cacheInMemory(true)        .cacheOnDisk(true)        ...        .build();ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used
2. You can use PauseOnScrollListener to prevent list (listview, grid, and so on) scrolling.
boolean pauseOnScroll = false; // or trueboolean pauseOnFling = true; // or falsePauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);listView.setOnScrollListener(listener);

Notes 1. The two permissions mentioned above must be added; otherwise, an error will occur.
2 . ImageLoaderConfiguration must be configured and initialized to initialize this configuration. ImageLoader. getInstance (). init (config); otherwise, an error message will appear.
3. ImageLoader determines the image width and height based on the height and width of the ImageView.
4. If OOM occurs frequently (what others see on the other side is very helpful)
① Reduce the thread pool size in the configuration (. threadPoolSize). 1-5 is recommended;
② Use. bitmapConfig (Bitmap. config. RGB_565) instead of ARGB_8888;
③ Use. imageScaleType (ImageScaleType. IN_SAMPLE_INT) or try. imageScaleType (ImageScaleType. EXACTLY );
④ Avoid using RoundedBitmapDisplayer. It will create a new Bitmap object in ARGB_8888 format;
⑤ Use. memoryCache (new WeakMemoryCache (), do not use. cacheInMemory ();

 

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.