Universal-image-loader parsing (i) detailed configuration of the--imageloaderconfiguration

Source: Internet
Author: User

This article mainly introduces the "Universal-image-loader Analysis (a)--imageloaderconfiguration detailed configuration", mainly related to Universal-image-loader analysis (a)-- Imageloaderconfiguration detailed configuration of the content, for Universal-image-loader resolution (a)--imageloaderconfiguration detailed configuration of interested students can refer to.

Universal-image-loader This open source framework to give us the benefit of, it is a picture loading framework, the main strength is that can be used for the network and other image source loading, and has a multi-cache mechanism. First give the project address: Https://github.com/nostra13/Android-Universal-Image-Loader

First, a brief description:

1. Multi-threaded download pictures, images can be from the network, file system, project folder assets and drawable medium
2. Support arbitrary configuration imageloader, such as thread pool, picture downloader, memory cache policy, hard disk cache policy, picture display options and some other configuration
3. Memory cache for image support, file system cache or SD card cache
4. Support the image download process monitoring
5. Crop the bitmap based on the size of the control (ImageView), reducing bitmap memory consumption
6. Better control the loading process of the picture, such as pause picture loading, restart loading picture, general use in Listview,gridview, pause loading picture during sliding, stop sliding to load picture
7. Provide loading of pictures on slower network

Second, configuration and use

1. Create a new class to inherit application, implement initialization Imageloader

Imageloader is a configuration scheme, primarily a one-time cache policy in a configuration project, so that the standalone configuration is easy to modularize.

@Override public    void OnCreate () {        //TODO auto-generated method stub        super.oncreate ();                Initialize the Imageloader          imageloader.getinstance (). Init (Imageloaderconfiguration configuration) by configuring the schema.  
    }

Here the parameter is a imageloaderconfiguration, this object can set the cache, cache path and so on, we first get a default configuration good object.

It uses the build mode so that we can easily come to a default configured Imageloaderconfiguration object

    /**     * Create a default Imageloader configuration parameter, which creates a default configuration scheme     * @return */    private imageloaderconfiguration Getdefaultconfig () {       imageloaderconfiguration config = Imageloaderconfiguration.createdefault( Getapplicationcontext ());       return config;    }    

Of course, Imageloaderconfiguration has multiple options to configure. The following are the various properties and their own default values

imageloaderconfiguration config = new Imageloaderconfiguration.builder (context). memorycacheextraoptions (480, 800)// Default = Device screen dimensions. Diskcacheextraoptions (480, +, compressformat.jpeg, and null). Taskexecuto      R (...)      . Taskexecutorforcachedimages (...) . ThreadPoolSize (3)//default. ThreadPriority (thread.norm_priority-1)//default. Tasksprocessingorder (Queuepr OCESSINGTYPE.FIFO)//default. Denycacheimagemultiplesizesinmemory (). MemoryCache (New Lrumemorycache (2 * 1024 * ). Memorycachesize (2 * 1024x768 * 1024x768). Memorycachesizepercentage (+)//default. DiskCache (New Unlimited Disccache (Cachedir))//default. Diskcachesize (* 1024x768). Diskcachefilecount (+). Diskcachefilenam      Egenerator (New Hashcodefilenamegenerator ())//default. Imagedownloader (new Baseimagedownloader (context))//default . Imagedecoder (New Baseimagedecoder ())//default. Defaultdisplayimageoptions (DisplayiMageoptions.createsimple ())//default. Writedebuglogs (). build (); 

Example

    /** * All configuration Parameters Example * @return */private Imageloaderconfiguration Getwholeconfig () {//Set default configuration, set cache,        Not set here can be set to another place displayimageoptions defaultoptions = new Displayimageoptions.builder (). Cacheinmemory (True)                . Cacheondisk (True). Build ();                    Set the path of the cache File Cachedir = storageutils.getowncachedirectory (Getapplicationcontext (), "Imageloader/cache"); imageloaderconfiguration config = new imageloaderconfiguration. Builder (Getapplicationcontext ()). Memorycacheextraoptions (480, 800)//The maximum length of each cache file saved. t Hreadpoolsize (3)//Line Cheng Chinega load quantity. ThreadPriority (thread.norm_priority-2)//explanation: When the same URI gets different large The small picture, cached to memory, only caches one. By default, several different sizes of the same picture are cached. Denycacheimagemultiplesizesinmemory ()//Deny caching multiple pictures: MemoryCache (new Wea Kmemorycache ())//cache policy you can implement through your own memory cache, here with weak references, the disadvantage is too easy to be recycled, not very good!. Memorycachesize (2 * 1024 * 1024)//Set the size of the memory cache. Diskcachesize (50 * 1024 * 1024)//Set disk cache size 50M. Diskcachefilenam Egenerator (New Md5filenamegenerator ())//will save the URI name with MD5 encryption. Tasksprocessingorder (Queueprocessingtype.li FO)//Set the picture to download and display the Work queue sort. Diskcachefilecount (100)//number of files cached. diskcache (New UNLIMITEDDISKCA Che (cachedir)//Custom cache path. Defaultdisplayimageoptions (defaultoptions)//Display the parameters of the picture, default: Displayimageoptions.cre Atesimple (). Imagedownloader (New Baseimagedownloader (this, 5 *, +))//ConnectTimeout (5 s), R   Eadtimeout (s) time-out. Writedebuglogs ()//Open debug Log. Build ();//Start building

return config; }

At first, don't be frightened away, actually look more, we generally just need to know what this is to do, and then according to their own needs configuration can.

Common configuration:

    /** * More commonly used configuration scheme * @return */private Imageloaderconfiguration Getsimpleconfig () {//Set the path of the cache                 File Cachedir = Storageutils.getowncachedirectory (Getapplicationcontext (), "Imageloader/cache"); imageloaderconfiguration config = new imageloaderconfiguration. Builder (Getapplicationcontext ()). Memorycacheextraoptions (480, 800)//The maximum length of each cache file that is saved. Threadprior ity (thread.norm_priority-2)//thread pool the number of threads. Denycacheimagemultiplesizesinmemory ()//disable caching of multiple pictures. Memoryc             Ache (new Lrulimitedmemorycache (40*1024*1024))//Cache policy. Memorycachesize (50 * 1024 * 1024)//Set the size of the memory cache . Diskcachefilenamegenerator (New Md5filenamegenerator ())//cache file name is saved in. diskcachesize (200 * 1024 * 1024)//disk cache large              Small. Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO)//Work queue. Diskcachefilecount (200)//number of files cached . DiskCache (New Unlimiteddiskcache (Cachedir))//Custom cache path//.WRitedebuglogs ()//Remove for release app. build ();    return config; }

Note: There are a number of parameters are open to discussion, their own according to the needs of the configuration can!

How to clear the cache in activity:

        Clear Cache        imageloader.getinstance (). Cleardiskcache ();        Imageloader.getinstance (). Clearmemorycache ();

Manifest.xml, and configure the application!

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.kale.universalimageloadertest "android:versioncode=" 1 "android:versionname=" 1.0 "> <!--permission to access the INTERNET--<uses-permission android:name= "Android.permission.INTERNET"/> <!--includ E Next permission If you want the UIL to the cache images on SD card--<!--write SD card permissions--<uses-perm Ission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-sdk android:minsdkversion= " 8 "android:targetsdkversion="/> <!--added to your application-<applicationandroid:name= "Com.kale.universalimageloadertest.application.MyApplication"Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android Oid:theme= "@style/apptheme" > <activity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <activity android:name=" Com.kale.universalima Geloadertest. Uillistactivity "/> </application></manifest>

Myapplication.java

Package Com.kale.universalimageloadertest.application;import Java.io.file;import Android.app.application;import Com.nostra13.universalimageloader.cache.disc.impl.unlimiteddiskcache;import Com.nostra13.universalimageloader.cache.disc.naming.md5filenamegenerator;import Com.nostra13.universalimageloader.cache.memory.impl.fifolimitedmemorycache;import Com.nostra13.universalimageloader.cache.memory.impl.lrulimitedmemorycache;import Com.nostra13.universalimageloader.cache.memory.impl.weakmemorycache;import Com.nostra13.universalimageloader.core.displayimageoptions;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;/** * @author: Jack Tony * @tips: Create a new MyApplication inheritance application , and create a configuration parameter for the Imageloader in OnCreate () *Number, and initialize to Imageloader code * @date: 2014-10-15 */public class MyApplication extends application{@Override public void O                       Ncreate () {//TODO auto-generated method stub super.oncreate ();      Initialize the Imageloader imageloader.getinstance (). Init (Getsimpleconfig ()) by configuring the schema. }/** * Creates a default Imageloader configuration parameter, which creates a default configuration scheme * @return * */private Imageloaderconfiguration Getdefault Config () {imageloaderconfiguration config = imageloaderconfiguration. Createdefault (Getapplicationco       ntext ());    return config; }/** * All configuration Parameters Example * @return */private Imageloaderconfiguration Getwholeconfig () {//Set default configuration, Set the cache, not set here can be set to another place displayimageoptions defaultoptions = new Displayimageoptions.builder (). Cacheinmemory (tr                UE). Cacheondisk (True). Build ();        Set the path of the cache File Cachedir = storageutils.getowncachedirectory (Getapplicationcontext (), "Imageloader/cache");            imageloaderconfiguration config = new imageloaderconfiguration. Builder (Getapplicationcontext ()). Memorycacheextraoptions (480, 800)//The maximum length of each cache file saved. t Hreadpoolsize (3)//Line Cheng Chinega load quantity. ThreadPriority (thread.norm_priority-2)//explanation: When the same URI gets different large The small picture, cached to memory, only caches one. By default, several different sizes of the same picture are cached. Denycacheimagemultiplesizesinmemory ()//Deny caching multiple pictures: MemoryCache (new Wea                  Kmemorycache ())//cache policy you can implement through your own memory cache, here with weak references, the disadvantage is too easy to be recycled, not very good!. Memorycachesize (2 * 1024 * 1024)//Set the size of the memory cache . diskcachesize (50 * 1024 * 1024)//Set disk cache size 50M. diskcachefilenamegenerator (New Md5fil Enamegenerator ())//The URI name of the saved time is encrypted with MD5. Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO)//Set up the work queue for picture download and display Diskcachefilecount (100)//cache file number. diskcache (new Unlimiteddiskcache (Cachedir))//Custom Slow Save path. DefaultdisplaYimageoptions (defaultoptions)//Display the parameters of the picture, default: Displayimageoptions.createsimple (). Imagedownloader (New Baseimag                  Edownloader (Getapplicationcontext (), 5 *, (+)))//ConnectTimeout (5 s), ReadTimeout (s) time-out    . Writedebuglogs ()//Open debug Log. Build ();//start building return config;         }/** * More common configuration scheme * @return */private Imageloaderconfiguration Getsimpleconfig () {//Set the path of the cache                 File Cachedir = Storageutils.getowncachedirectory (Getapplicationcontext (), "Imageloader/cache"); imageloaderconfiguration config = new imageloaderconfiguration. Builder (Getapplicationcontext ()). Memorycacheextraoptions (480, 800)//The maximum length of each cache file that is saved. Threadprior ity (thread.norm_priority-2)//thread pool the number of threads. Denycacheimagemultiplesizesinmemory ()//disable caching of multiple pictures. Memoryc Ache (New Lrulimitedmemorycache (50 * 1024 * 1024))//Cache policy. Memorycachesize (50 * 1024 * 1024)//SetThe size of the memory cache. Diskcachefilenamegenerator (new Md5filenamegenerator ())//cache file name is saved. Diskcachesize (200 * 1  024 * 1024)///disk cache size. Tasksprocessingorder (QUEUEPROCESSINGTYPE.LIFO)//Work queue. Diskcachefilecount (200) The number of files cached. DiskCache (new Unlimiteddiskcache (Cachedir))//Custom cache path//.writedebuglogs ()//Remove         For release app. build ();    return config; }/* Imageloaderconfiguration config = new Imageloaderconfiguration.builder (context). Memorycacheex Traoptions (480, +)//default = Device screen dimensions. Diskcacheextraoptions (480, 75, Compressformat.jpeg,      NULL). Taskexecutor (...)      . Taskexecutorforcachedimages (...) . ThreadPoolSize (3)//default. ThreadPriority (thread.norm_priority-1)//default. Tasksprocessingorder (Queuepr OCESSINGTYPE.FIFO)//default. Denycacheimagemultiplesizesinmemory (). MemoryCache (New Lrumemorycache (2 * 1024 *   1024))   . memorycachesize (2 * 1024x768). Memorycachesizepercentage (+)//default. DiskCache (New Unlimiteddisccache (Cachedir)) Default. Diskcachesize (* 1024x768). Diskcachefilecount (+) Diskcachefilenamegenerator (new Hashco Defilenamegenerator ())///default. Imagedownloader (new Baseimagedownloader (context))//default. Imagedecoder (NE W Baseimagedecoder ())//default. Defaultdisplayimageoptions (Displayimageoptions.createsimple ())//default. WRI  Tedebuglogs (). build (); */}

Universal-image-loader's Memory cache policy

Detailed caching strategy can be: http://blog.csdn.net/xiaanming/article/details/27525741, below is the result of the summary:


1. Strong reference Caching
Lrumemorycache (This class is the default memory cache class for the open source framework, which caches the strong references of bitmap)

Benefits: Pictures will not easily be erased when sliding, experience good; Disadvantages: prone to Oom


2. A cache with strong references and weak references
Usingfreqlimitedmemorycache (if the total number of cached pictures exceeds the limit, first delete the bitmap with the least frequency)
Lrulimitedmemorycache (This is also used by the LRU algorithm, and Lrumemorycache is different, he caches the weak references of bitmap)
Fifolimitedmemorycache (FIFO-First cache policy, when the set value is exceeded, first delete the bitmap that is first added to the cache)
Largestlimitedmemorycache (Delete the largest bitmap object first when exceeding the cache limit)
Limitedagememorycache (when the bitmap is added to the cache more than the value we set, delete it)


3. Use only weak reference caching
Weakmemorycache (there is no limit to the total size of this type of cache bitmap, the only thing that is not stable, cached images are easily recycled)

Benefits: No limit to the total size of the cache bitmap; disadvantage: make the picture unstable, the picture is extremely easy to be recycled

Note: Do not use. Cacheinmemory ();

Universal-image-loader's hard disk cache policy

Detailed hard disk cache strategy can be: http://blog.csdn.net/xiaanming/article/details/27525741, below is the summary of the results:

Filecountlimiteddisccache (can set the number of cached pictures, when the set value is exceeded, delete the first file added to the hard disk)
Limitedagedisccache (the maximum time to set the file to survive, and when this value is exceeded, delete the file)
Totalsizelimiteddisccache (Sets the maximum value of the cache bitmap, when the value is exceeded, delete the file that was first added to the hard disk)
Unlimiteddisccache (there is no limit to this cache class)

Diskcachesize and Diskcachefilecount are configured in Imageloaderconfiguration, he uses lrudisccache, otherwise unlimiteddisccache

In the latest source code also has a hard disk cache class can be configured, that is Limitedagedisccache, can be in the Imageloaderconfiguration.diskcache (...) Configuration

Avoid Oom

To avoid oom, you can modify the following configuration scenarios:

. Memorycacheextraoptions (480, 800)//The maximum length and width of each cache file that is saved, the size is self-formulated

. ThreadPriority (thread.norm_priority-2)//thread pool The number of threads, general configuration 1-5, here is 3

. MemoryCache (New Lrulimitedmemorycache (40*1024*1024))//Change cache policy, can use weak reference

Reference from:

http://blog.csdn.net/xiaanming/article/details/26810303

http://blog.csdn.net/xiaanming/article/details/27525741

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

Universal-image-loader parsing (i) detailed configuration of the--imageloaderconfiguration

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.