The development of the application process, it is unavoidable to carry out network request operation for data exchange, such as downloading pictures, if you write a download image of the class to operate, to consider too much content, must thread pool, memory overflow, picture disk cache operation, picture memory cache operation, etc., quite troublesome. Fortunately, the great open source has written a relatively perfect open source class library for everyone to use Android-universal-image-loader, this class library has been used by many well-known software, when I myself use this open source class library, Baidu a big push, have viewed official documents. Now write down the records for your reference.
First, Introduction:
The purpose of Android-universal-image-loader is to provide a powerful, flexible, highly customizable image loading, caching and display tool. It provides a number of configuration options and gives you good control over image loading and caching.
features of the class library
L Multi-threaded image loading (synchronous or asynchronous)
L Flexible Image loading configuration options (thread execution, download, decode, memory and disk cache, image display options)
L Customize the configuration of each display image
L cache in memory or on disk (device memory or SD card)
L Monitor the loading process (including download progress)
Second, usage
First look at the introduction of this class package, load the picture of the running flowchart
As you can see, there are three different situations when loading pictures:
(Post process bitmap a step, is actually the image processing, such as watermark, fillet and so on, the framework does not give a concrete implementation, the default is null, if necessary to implement, so the analysis can be ignored)
1. Picture is cached in memory: Displays the image directly.
2. The picture is cached on disk: It is decoded first, then temporarily cached in memory, and finally displayed.
3. The picture is not cached: first downloaded, then cached to disk and memory, and finally displayed.
(i) Include Library
Download the dependent Jar package, import the project under the Libs folder and add to the project path.
(ii) Additional rights
<manifest> <!--Include following permission if you load images from Internet-- < Uses-permission android:name= "Android.permission.INTERNET"/> <!--Include following permission if you want To cache images on SD card-- <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/ > ...</manifest>
(iii) global configuration
Global configuration I typically write a class that inherits application and then declares it in the Mainfest file
public class MyApplication extends application {@Overridepublic void OnCreate () {//TODO auto-generated method stubsuper.o Ncreate (); Initimageloader (Getapplicationcontext ());} public static void Initimageloader (context context) {File Cachedir = storageutils.getcachedirectory (context); mageloaderconfiguration config = new Imageloaderconfiguration.builder (context). memorycacheextraoptions (480, 800)/ /default = Device screen dimensions. Diskcacheextraoptions (480, + null)//. Taskexecutor (...) . Taskexecutorforcachedimages (...) . ThreadPoolSize (3)//default. ThreadPriority (thread.norm_priority-2)//default. Tasksprocessingorder (Que UEPROCESSINGTYPE.FIFO)//default. Denycacheimagemultiplesizesinmemory ()//. MemoryCache (New Lrumemorycache (2 * 1024x768). Memorycachesize (2 * 1024x768 * 1024x768). Memorycachesizepercentage (+)//default. DISKCAC He (new Unlimiteddisccache (Cachedir))//default. diskcachesizE (* 1024x768). Diskcachefilecount (+). Diskcachefilenamegenerator (New Hashcodefilenamegenerator ())// Default. Imagedownloader (new Baseimagedownloader (context))//default//. Imagedecoder (New Baseimagedecoder ( )//default. Defaultdisplayimageoptions (Displayimageoptions.createsimple ())//default. Writedebuglogs () . build ();//Initialize Imageloader with configuration. Initialize Configuration imageloader.getinstance (). init (config);}}
<application android:name= ". Base. MyApplication " android:allowbackup=" true " android:icon=" @drawable/ic_launcher " android:label=" @ String/app_name " android:theme=" @style/apptheme ">
Most of the above configuration has default values, according to their own needs to configure, no need to write all, now the display configuration is the same.
(iv) Display configuration
Display configuration is specific to each display picture task's configuration
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)//Resour Ce or drawable. Resetviewbeforeloading (FALSE)//default. delaybeforeloading (+). Cacheinmemory (FA LSE)//DEFAULT. Cacheondisk (FALSE)//default. Preprocessor (...) . Postprocessor (...) . Extrafordownloader (...) . Considerexifparams (FALSE)///default. Imagescaletype (imagescaletype.in_sample_power_of_2)//default. Bitma Pconfig (Bitmap.Config.ARGB_8888)//default. Decodingoptions (...) . Displayer (New Simplebitmapdisplayer ())//default. Handler (new handler ())//default. Build ();
(v) Use of the finished configuration
Display with default configuration: Imageloader.getinstance (). DisplayImage (ImageUrl, ImageView);
Display with custom configuration:imageloader.getinstance (). DisplayImage (ImageUrl, imageview,options);
Display with listener events:
Imageloader.displayimage (IMAGEURL, ImageView, Options, new Imageloadinglistener () { @Override public Void Onloadingstarted () { ///Start load Execution } @Override public void onloadingfailed (Failreason failreason) { //load fails to execute } @Override public void Onloadingcomplete (Bitmap loadedimage) { //execute} When load succeeds @Override public void onloadingcancelled () { //load Cancel execution }});
Display with monitoring event and progress bar:
Imageloader.displayimage (Imageuri, ImageView, Options, new Imageloadinglistener () { @Override public Void Onloadingstarted (String Imageuri, view view) { ... } @Override public void onloadingfailed (String imageuri, view view, Failreason Failreason) { ... } @Override public void Onloadingcomplete (String imageuri, view view, Bitmap loadedimage) { ... } @Override public void onloadingcancelled (String imageuri, view view) { ... }}, new Imageloadingprogresslistener () { @Override public void Onprogressupdate (String imageuri, view view, int Current, int total) { ... }});
Some articles suggest loading local images also useimageloader.getinstance (). DisplayImage, there is absolutely no need.
third, the matters needing attention 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 oom often occurs
① 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 analysis of the source code of this kind of library can refer to this article of the Great God http://blog.csdn.net/xiaanming/article/details/39057201
Android-universal-image-loader Pictures The use of asynchronous load class libraries