Android open-source framework Universal-Image-Loader, androidsdkloader

Source: Internet
Author: User

Android open-source framework Universal-Image-Loader, androidsdkloader

If you want to comment on which Image open-source library is the most widely used, I think it should be called Universal-Image-Loader.

If you decompile a few items at will, you can basically see the figure, it is like an image loading guardian, silently guarding the image loading. I believe many

This asynchronous image loading framework is not very familiar yet. In addition, it has been optimized in several places recently, and most of the information on the Internet is still in the past.

After several days, I have studied the open-source framework Universal-Image-Loader (in fact, it is used in recent projects, and I have carefully considered various situations.

Situation), hope to help new users, but also hope you can give me some advice.


Github Address link for the project: https://github.com/nostra13/Android-Universal-Image-Loader

If you cannot log on to Github, you can download the link here: Click


I. features:

1. multi-thread asynchronous loading and display of images (images are from the network, SD card, assets folder, drawable folder (9 patch cannot be loaded), and video thumbnails are added)

"http://site.com/image.png" // from Web"file:///mnt/sdcard/image.png" // from SD card"file:///mnt/sdcard/video.mp4" // from SD card (video thumbnail)"content://media/external/images/media/13" // from content provider"content://media/external/video/media/13" // from content provider (video thumbnail)"assets://image.png" // from assets"drawable://" + R.drawable.img // from drawables (non-9patch images)

2. You can use listener to monitor the loading process and Pause image loading. In ListView and GridView that are frequently used, you can set the sliding period.

Stop loading and load images when stopping sliding (easy to save traffic and can be used in some optimizations)

3. You can cache images to memory more efficiently.

4. highly customizable (various configurations can be made as needed, such as the thread pool, image downloader, and memory cache policy)

5. Supports image memory cache and SD card (File) Cache

6. When the network speed is low, you can also load images and Set Download listening.


Ii. configuration details

1. Download the jar package and put it in the libs folder.

Note: Maven dependency:

<dependency>    <groupId>com.nostra13.universalimageloader</groupId>    <artifactId>universal-image-loader</artifactId>    <version>1.9.3</version></dependency>

Gradle dependency:

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'

2. AndroidManifest. xml

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

3. Configure the ImageLoaderConfiguration parameter in the application (only one configuration is allowed. If multiple configurations are performed, the first configuration parameter is used by default)

A. Use the default settings

ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);  

B. Configure parameters by yourself

File cacheDir = StorageUtils. getCacheDirectory (context); // cache folder path ImageLoaderConfiguration config = new ImageLoaderConfiguration. builder (context ). memoryCacheExtraOptions (480,800) // default = device screen dimensions maximum length and width of the memory cache file. diskCacheExtraOptions (480,800, null) // detailed information of the local cache (maximum length and width of the cache), it is best not to set this. taskExecutor (...). taskExecutorForCachedImages (...). threadPoolSize (3) // Number of threads loaded in the default thread pool. threadPriority (Thread. NORM_PRIORITY-2) // default specifies the priority of the current thread. tasksProcessingOrder (QueueProcessingType. FIFO) // default. denyCacheImageMultipleSizesInMemory (). memoryCache (new LruMemoryCache (2*1024*1024) // you can use your own memory cache. memoryCacheSize (2*1024*1024) // maximum value of the memory cache. memoryCacheSizePercentage (13) // default. diskCache (new UnlimitedDiscCache (cacheDir) // default allows you to customize the cache path. diskCacheSize (50*1024*1024) // maximum cached value of 50 Mb SD card (local. diskCacheFileCount (100) // number of files that can be cached // default indicates that UIL is encrypted and named using HASHCODE. MD5 (new Md5FileNameGenerator () can also be used. diskCacheFileNameGenerator (new HashCodeFileNameGenerator ()). imageDownloader (new BaseImageDownloader (context) // default. imageDecoder (new BaseImageDecoder () // default. defaultDisplayImageOptions (DisplayImageOptions. createSimple () // default. writeDebugLogs () // print the debug log. build (); // start building

After ImageLoaderConfiguration is configured, do not forget to initialize the application)

ImageLoader.getInstance().init(config);
Note: Please configure the above configurations according to your own needs. Not all configurations are required.


4. Image Display

A. first obtain the ImageLoader instance (using the singleton mode)

ImageLoader imageLoader = ImageLoader.getInstance(); 

Note: In each display task (the layout must be instantiated before relevant operations can be performed.

B. Related display parameter configuration

DisplayImageOptions options = new DisplayImageOptions. builder (). showImageOnLoading (R. drawable. ic_stub) // sets the image displayed during image download. showImageForEmptyUri (R. drawable. ic_empty) // sets the image to be displayed when the image Uri is null or incorrect. showImageOnFail (R. drawable. ic_error) // sets the picture that is incorrectly displayed during image loading or decoding. resetViewBeforeLoading (false) // default specifies whether to reset or reset the image before loading. delayBeforeLoading (1000) // the delay before the download. cacheInMemory (false) // default specifies whether the downloaded image is cached in memory. cacheOnDisk (false) // default specifies whether the downloaded image is cached in the SD card. preProcessor (...). postProcessor (...). extraForDownloader (...). considerExifParams (false) // default. imageScaleType (ImageScaleType. IN_SAMPLE_POWER_OF_2) // default specifies how the image is encoded. bitmapConfig (Bitmap. config. ARGB_8888) // set the image decoding type by default. decodingOptions (...) // decode the image. displayer (new SimpleBitmapDisplayer () // default You can also set the rounded corner image new RoundedBitmapDisplayer (20 ). handler (new Handler () // default. build ();

NOTE: If DisplayImageOption is not passed to ImageLoader. displayImage (...) Method, the default display options from the configuration
(ImageLoaderConfiguration. defaultDisplayImageOptions (...)) Will be used.

1 ). imageScaleType (ImageScaleType imageScaleType) // sets the image scaling mode. The scale type is mageScaleType: EXACTLY. The image will be scaled down in proportion to the target size. EXACTLY_STRETCHED: The image will be scaled to the target size completely: the image will be an integer multiple of the Secondary Sampling. IN_SAMPLE_POWER_OF_2: The image will be reduced by 2 times until the next step is reduced, so that the image size is smaller. NONE: The image will not be adjusted. 2 ). displayer (BitmapDisplayer displayer) // sets the display mode of the image. displayer: RoundedBitmapDisplayer (int roundPixels) sets the FakeBitmapDisplayer () class to set the rounded corner image. FadeInBitmapDisplayer (int durationMillis) set the time when the image is gradually displayed. SimpleBitmapDisplayer () shows an image normally.

Parameter supplement:

. ConsiderExifParams (true) // whether to consider the JPEG image EXIF parameter (rotation, flip). displayer (new FadeInBitmapDisplayer (100) // The animation time after the image is loaded

C. display images

1、ImageLoader.getInstance().displayImage(uri, imageView);2、ImageLoader.getInstance().displayImage(uri, imageView, options);3、ImageLoader.getInstance().displayImage(uri, imageView, listener);4、ImageLoader.getInstance().displayImage(uri, imageView, options, listener);5、ImageLoader.getInstance().displayImage(uri, imageView, options, listener, progressListener);


Parameter Parsing:

ImageUrl: the URL of the image. imageView: specifies the ImageView control of the image. options DisplayImageOptions: Specifies the configuration information. listener of the listener image download status. progressListener: listener of the image download progress.

1) Method 1: The simplest way is to define the URL of the image to be displayed and the ImageView of the image to be displayed. In this case, the default settings are used for the image display options.

2) Method 2: load an image of the custom configuration

3) method 3: attach an image with a listener

4) Method 4: load a custom configuration with an image monitored

5) Method 5: load a custom configuration with a listener and a progress bar

ImageLoader. getInstance (). displayImage (uri, imageView, options, new ImageLoadingListener () {@ Overridepublic void onLoadingStarted (String arg0, View arg1) {// start loading} @ Overridepublic void onLoadingFailed (String arg0, view arg1, FailReason arg2) {// loading Failed} @ Overridepublic void onLoadingComplete (String arg0, View arg1, Bitmap arg2) {// loading successful} @ Overridepublic void onLoadingCancelled (String arg0, view arg1) {// cancel loading }}, new ImageLoadingProgressListener () {@ Overridepublic void onProgressUpdate (String imageUri, View, int current, int total) {// loading progress }});

Iii. Tips and skills

1. You must configure maxImageWidthForMemoryCach (...) and

MaxImageHeightForMemoryCache (...) parameters, such as image enlargement. In other cases, you do not need to perform these configurations because

The specified configuration will process Bitmap in the memory-saving mode based on the screen size.

2. It is wise to configure the thread pool size in settings. A large thread pool allows multiple threads to work simultaneously, but it also significantly affects the UI

Thread speed. However, you can set a lower priority: When ImageLoader is in use, it can reduce its priority.

The UI thread will be smoother. When using List, the UI thread is often not smooth, so it is best to set threadPoolSize (...) and

ThreadPriority (...) parameters to optimize your application.

3. memoryCache (...) and memoryCacheSize (...) parameters will overwrite each other, so you can use one in ImageLoaderConfiguration.

4. diskCacheSize (...), diskCache (...), and diskCacheFileCount (...) parameters will overwrite each other and only use one

Note: Do not use discCacheSize (...), discCache (...), and discCacheFileCount (...).

5. If the parameters you pass in when using the displayImage () method in your program are often the same, a reasonable solution is to set these options

Configure the settings in ImageLoader as the default option (by calling the defaultDisplayImageOptions (...) method ). Call later

The displayImage (...) method does not have to specify these options. If these options are not explicitly specified

DefaultDisplayImageOptions (...) method, the default UIL settings will be called during the call.


Iv. Notes

1. If you frequently see oom, you can try:

1) Disable cache cacheInMemory (false) in the memory. If oom still occurs, it seems that your application has a memory leak and uses MemoryAnalyzer to detect it. Otherwise, try the following steps (try all or a few)

2) reduce the size of the configured thread pool (.threadPoolSize(...)), Recommended 1 ~ 5

3) use. bitmapConfig (Bitmap. Config. RGB_565) in the display options. The RGB_565 mode consumes twice less memory than the ARGB_8888 mode.

4) use. diskCacheExtraOptions (480,320, null) in configuration)

5) use. memoryCache (newWeakMemoryCache () or completely disable the cache in the memory (don't call. cacheInMemory ()).

6) use. imageScaleType (ImageScaleType. EXACTLY) or. imageScaleType (ImageScaleType. IN_SAMPLE_INT) in the display options)

7) Avoid using RoundedBitmapDisplayer. it creates a new Bitmap object to display in ARGB-8888 mode when calling, for memory cache mode (ImageLoaderConfiguration. memoryCache (...)) you can use the implemented method.

2. ImageLoader determines the image width and height based on the height and width of the ImageView.

3. You must initialize ImageLoaderConfiguration. Otherwise, an error is reported.

4. After caching is enabled, the external SD card address (/sdcard/Android/data/[package_name]/cache) is cached by default ). if the external SD card does not exist, it will be cached to the mobile phone. the cached data to the SD card must be stored in AndroidManifest. configure the following in the xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

5. The following methods can be used in the memory cache mode (ImageLoaderConfiguration. memoryCache (...))

1) cache only uses strong references

LruMemoryCache (when the cache size exceeds the specified value, the least recently used bitmap will be deleted)-by default

2) use weak references and strong references in the cache

UsingFreqLimitedMemoryCache (when the cache size exceeds the specified value, the minimum bitmap is deleted) LRULimitedMemoryCache (when the cache size exceeds the specified value, the minimum recently used <span style = "font-family: 'helvetica Neue ', Helvetica, 'segoe Ui', Arial, freesans, sans-serif; "> bitmap) -- default value </span> specified olimitedmemorycache (when the cache size exceeds the specified value, <span style = "font-family: 'helvetica Neue ', Helvetica, 'segoe Ui', Arial, freesans, sans-serif;"> bitmap) </span> LargestLimitedMemoryCache (when the cache size exceeds the specified value, the maximum bitmap is deleted) LimitedAgeMemoryCache (when the cache object exceeds the defined time, It is deleted)

3) Use Weak references in cache

WeakMemoryCache (no restriction on cache)

6. The local cache mode can be implemented using the following methods (ImageLoaderConfiguration. diskCache (...))

UnlimitedDiskCache does not limit the cache size (default) TotalSizeLimitedDiskCache (sets the total cache size, when the cache is deleted before the longest) FileCountLimitedDiskCache (sets the total number of cache files when the alert value is reached, delete the cache that has elapsed before. If the file size is the same, you can use this mode) LimitedAgeDiskCache (no restriction on the cache size, but set the cache time and delete it after expiration)

V. Perfect example (reference source code)

1. Project Structure


Constans is mainly used to store the image url

2. Project


3. Code explanation

1) add permissions

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

2) initialize the configuration

Package com. xwj. imageloaderdemo; import java. io. file; import android. app. application; import android. content. context; import com. nostra13.universalimageloader. cache. disc. impl. unlimitedDiscCache; import com. nostra13.universalimageloader. cache. disc. naming. md5FileNameGenerator; import com. nostra13.universalimageloader. cache. memory. impl. usingFreqLimitedMemoryCache; import com. nostra13.universalimageloader. core. imageLoader; import com. nostra13.universalimageloader. core. imageLoaderConfiguration; import com. nostra13.universalimageloader. core. assist. queueProcessingType; import com. nostra13.universalimageloader. core. download. baseImageDownloader; import com. nostra13.universalimageloader. utils. storageUtils; public class ImageLoaderApplication extends Application {public void onCreate () {super. onCreate (); initImageLoader (getApplicationContext ();} public static void initImageLoader (Context context) {// File cacheDir = StorageUtils. getOwnCacheDirectory (context, "imageloader/Cache"); ImageLoaderConfiguration config = new ImageLoaderConfiguration. builder (context ). memoryCacheExtraOptions (480,800) // max width, max height, that is, the maximum length and width of each cached file. threadPoolSize (3) // Number of threads loaded in the thread pool. threadPriority (Thread. NORM_PRIORITY-2 ). denyCacheImageMultipleSizesInMemory (). diskCacheFileNameGenerator (new Md5FileNameGenerator () // encrypt the URI name stored with MD5. memoryCache (new UsingFreqLimitedMemoryCache (2*1024*1024) // You can pass your own memory cache implementation/You can implement it through your own memory cache. memoryCacheSize (2*1024*1024) // maximum value of the memory cache. diskCacheSize (50*1024*1024) // maximum cached value of 50 Mb SD card (local. tasksProcessingOrder (QueueProcessingType. LIFO) // The original discCache-> diskCache. diskCache (new UnlimitedDiscCache (cacheDir) // customize the cache path. imageDownloader (new BaseImageDownloader (context, 5*1000, 30*1000) // connectTimeout (5 s), readTimeout (30 s) Timeout time. writeDebugLogs () // Remove for release app. build (); // initialize the ImageLoader configuration globally. getInstance (). init (config );}}
Note: 1. Remember to add android: name = "com. xwj. imageloaderdemo. ImageLoaderApplication" to AndroidManifest. xml"

2. Custom cache directory

3) initialize the display Configuration

// Use DisplayImageOptions. builder () Create DisplayImageOptionsoptions = new DisplayImageOptions. builder (). showImageOnLoading (R. drawable. ic_stub) // sets the image displayed during image download. showImageForEmptyUri (R. drawable. ic_empty) // sets the image to be displayed when the image Uri is null or incorrect. showImageOnFail (R. drawable. ic_error) // sets the picture that is incorrectly displayed during image loading or decoding. cacheInMemory (true) // sets whether the downloaded image is cached in memory. cacheOnDisk (true) // sets whether the downloaded image is cached in the SD card. displayer (new RoundedBitmapDisplayer (20) // set it to a rounded image. build (); // build complete

4) display images

imageLoader.displayImage(imageUrls[position],viewHolder.image, options);

5) Clear Cache

Public void onClearMemoryClick (View view) {Toast. makeText (this, "memory cache cleared successfully", Toast. LENGTH_SHORT ). show (); ImageLoader. getInstance (). clearMemoryCache (); // clear memory cache} public void onClearDiskClick (View view) {Toast. makeText (this, "the local cache is cleared successfully", Toast. LENGTH_SHORT ). show (); ImageLoader. getInstance (). clearDiskCache (); // clear the local cache}

The rest of the code is more common, so we will not introduce it more. The next article will describe the various application scenarios of Universal-Image-Loader in detail.


Download source code: Click


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.