Reprint Please indicate this article from Xiaanming's blog (http://blog.csdn.net/xiaanming/article/details/26810303 ). Please respect the fruits of others ' hard work, thank you!
Hello everyone! Almost the same two months did not write the article. The previous time is also in the busy change work, prepares the written interview what the thing, now new job to find good, new work oneself also more comfortable. The only pity is to go to a new city, new environment, New beginning. Hope that they can adapt to the new environment as soon as possible, and now in preparation for the handover of things, oneself also have some time, so continue to share the android aspects of things.
I believe that when you do Android applications, how many will be exposed to asynchronous loading images, or loading a large number of images of the problem. and loading pictures We often encounter a lot of problems, such as the image of the disorder. Oom and other issues, for beginners, these problems will be more difficult to solve, so there are a lot of open-source image loading framework came into being, the more famous is Universal-image-loader. Believe that a lot of friends have heard or used this powerful image loading framework, today this article is the basic introduction and use of this framework, mainly to help those who have not used this framework of friends.
This project exists on GitHub above Https://github.com/nostra13/Android-Universal-Image-Loader, we can first look at the characteristics of this open source library
- Multi-threaded Download pictures. Images can be derived from the network, file system, project folder assets and drawable medium
- Support arbitrary configuration imageloader, such as thread pool, picture downloader. Memory cache policy, hard disk cache policy. Picture display options and a few other configurations
- Memory cache for image support, file system cache or SD card cache
- Support for monitoring the image download process
- Bitmap is cropped according to the size of the control (ImageView). Reduce bitmap to consume too much memory
- Good control of the loading process of the picture, such as pausing the image loading, and then start loading pictures, generally used in the Listview,gridview, the sliding process to pause loading pictures, stop the slide when you load the picture
- Provides loading of pictures on slower networks
Of course, the features listed above may not be complete, to understand some of the other features can only be slowly discovered through our use, then we will look at the simple use of this open source library
Create a new Android project and download the jar package to add to the Projectlibs folder
Create a new MyApplication that inherits application and creates a Imageloader configuration parameter in OnCreate () and initializes it to Imageloader code such as the following
Package Com.example.uil;import Com.nostra13.universalimageloader.core.imageloader;import Com.nostra13.universalimageloader.core.imageloaderconfiguration;import Android.app.application;public Class MyApplication extends Application {@Overridepublic void OnCreate () {super.oncreate ();// Create default Imageloader configuration parameters imageloaderconfiguration Configuration = Imageloaderconfiguration.createdefault (this);// Initialize imageloader with configuration. Imageloader.getinstance (). init (configuration);}}
Imageloaderconfiguration is the configuration parameter of the picture loader imageloader, using the builder mode, where the Createdefault () is used directly method to create a default imageloaderconfiguration, and of course we are able to set the imageloaderconfiguration ourselves. Settings such as the following
File Cachedir = storageutils.getcachedirectory (context); Imageloaderconfiguration config = new Imageloaderconfiguration.builder (context). Memorycacheextraoptions (480, +)//default = Device screen dimensions . diskcacheextraoptions (480, +, compressformat.jpeg, or null). Taskexecutor (...) . Taskexecutorforcachedimages (...) . ThreadPoolSize (3)//default. ThreadPriority (thread.norm_priority-1)//default. Tasksprocessingorder (Que UEPROCESSINGTYPE.FIFO)//default. Denycacheimagemultiplesizesinmemory (). MemoryCache (New Lrumemorycache (2 * 1024x768). Memorycachesize (2 * 1024x768). Memorycachesizepercentage (+)//default. diskcache (New Unlimiteddisccache (Cachedir))//default. Diskcachesize (* 1024x768). Diskcachefilecount (100) . Diskcachefilenamegenerator (New Hashcodefilenamegenerator ())//default. Imagedownloader (New Baseimagedownloader (context)) Default. Imagedecoder (New Baseimagedecoder ())//default. Defaultdisplayimageoptions (Displayimageoptions.createsimple ())// Default. Writedebuglogs (). build ();
These are all the option configurations. We do not need to set each in the project ourselves, generally using createdefault () created by the imageloaderconfiguration can be used, The Imageloader init () method is then called to pass the imageloaderconfiguration parameter, imageloader using singleton mode.
Configuring Android Manifest files
<manifest> <uses-permission android:name= "Android.permission.INTERNET"/> <!--Include Next Permission if you want to allow UIL to the cache images on SD card-- <uses-permission android:name= "Android.permis Sion. Write_external_storage "/> ... <application android:name= "MyApplication" > ... </application></manifest>
Then we can load the picture, first we define the activity layout file
<?xml version= "1.0" encoding= "Utf-8"?><framelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Fill_ Parent " android:layout_height=" fill_parent "> <imageview android:layout_gravity=" center " Android:id= "@+id/image" android:src= "@drawable/ic_empty" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content"/></framelayout>
There was only one imageview, very easy, and then we went to load the picture. We will find that Imagelader provides several images to load the method, mainly of these displayimage (), LoadImage (), Loadimagesync (). The Loadimagesync () method is synchronous, and android4.0 has a feature. The network operation cannot be in the main thread, so the Loadimagesync () method we do not use
.
LoadImage () Loading pictures
We first use Imageloader's LoadImage () method to load the network image
Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg "; Imageloader.getinstance (). LoadImage (ImageUrl, New Imageloadinglistener () {@Overridepublic void onloadingstarted (String imageuri, view view) {} @Overridepublic void onloadingfailed (string imageuri, view view, Failreason Failreason) {} @Overridepublic void Onloadingcomplete (String imageuri, view view, Bitmap loadedimage) { Mimageview.setimagebitmap (loadedimage);} @Overridepublic void onloadingcancelled (String imageuri, view view) {}});
The URL and Imageloaderlistener of the incoming picture, set Loadedimage to ImageView in the callback method Onloadingcomplete (), Assuming you think the incoming imageloaderlistener is too complex, we can use the Simpleimageloadinglistener class, which provides an empty implementation of the Imageloaderlistener interface method, using the default adapter mode
Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg "; Imageloader.getinstance (). LoadImage (ImageUrl, New Simpleimageloadinglistener () {@ overridepublic void Onloadingcomplete (String imageuri, View view,bitmap loadedimage) {Super.onloadingcomplete ( Imageuri, view, loadedimage); Mimageview.setimagebitmap (loadedimage);});
Suppose we want to specify the size of the picture what to do, this is good, initialize a ImageSize object, specify the width and height of the picture. Code such as the following
Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg "; ImageSize mimagesize = new ImageSize (+), imageloader.getinstance (). LoadImage (IMAGEURL , Mimagesize, New Simpleimageloadinglistener () {@Overridepublic void Onloadingcomplete (String imageuri, view view, Bitmap loadedimage) {super.onloadingcomplete (Imageuri, view, loadedimage); Mimageview.setimagebitmap (loadedImage);}});
The above is just very easy to use Imageloader to load the network pictures, in the actual development, we do not use this way, how can we use the ordinary? We'll use the displayimageoptions. He is able to configure some of the image display options, such as the image displayed in ImageView in the load, whether it is necessary to use the memory cache, whether the file cache is needed, and so on. The configurations available for our selection such as the following
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. Cacheinmemory (FALSE)//default . Cacheondisk (FALSE)///default . Preprocessor (...) . Postprocessor (...) . Extrafordownloader (...) . Considerexifparams (FALSE)//default. Imagescaletype (imagescaletype.in_sample_power_of_2)//default . Bitmapconfig (Bitmap.Config.ARGB_8888)//default . Decodingoptions (...) . Displayer (New Simplebitmapdisplayer ())//default. Handler (new handler ())//default . Build ();
We'll make a slight change to the above code.
Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg "; ImageSize mimagesize = new ImageSize (100, 100);//Display picture configuration displayimageoptions options = new Displayimageoptions.builder (). Cacheinmemory (True). Cacheondisk (True). Bitmapconfig (Bitmap.Config.RGB_565). Build ( ); Imageloader.getinstance (). LoadImage (ImageUrl, Mimagesize, Options, new Simpleimageloadinglistener () {@ overridepublic void Onloadingcomplete (String imageuri, View view,bitmap loadedimage) {Super.onloadingcomplete ( Imageuri, view, loadedimage); Mimageview.setimagebitmap (loadedimage);});
We used displayimageoptions to configure some options for displaying pictures. Here I am. Caching images into memory has been cached in the file system so that we do not have to worry about loading images from the network every time, is not very convenient, but some options in the Displayimageoptions option for the LoadImage () method is not valid. For example, showimageonloading, Showimageforemptyuri, etc.
DisplayImage () Loading pictures
Next we'll take a look at the network image loading there is also a method displayimage (), code such as the following
Final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String IMAGEURL = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A% 252520photographer.jpg ";//Display picture configuration displayimageoptions options = new Displayimageoptions.builder (). Showimageonloading (r.drawable.ic_stub). Showimageonfail (R.drawable.ic_error). Cacheinmemory (True). CacheOnDisk ( true). Bitmapconfig (Bitmap.Config.RGB_565). build (); Imageloader.getinstance (). DisplayImage (ImageUrl, Mimageview, Options);
From the code above, we can see that using displayimage () is much more convenient than using LoadImage (), and there is no need to join the Imageloadinglistener interface, and we do not need to manually set the ImageView display bitmap object. Directly to the ImageView as a reference to the DisplayImage (), in the image display configuration options, we added a picture loaded in the ImageView above the picture shown above. and a picture loaded with an incorrect display. Effects such as the following, just beginning to display the ic_stub picture, assuming that the picture loaded successfully display pictures. Load Generating Error display Ic_error
This method is relatively convenient to use, and using the DisplayImage () method He will be based on the size of the control and imagescaletype to actively crop the image, we change the MyApplication, turn on log printing
public class MyApplication extends application {@Overridepublic void OnCreate () {super.oncreate ();// Create a default Imageloader configuration parameter imageloaderconfiguration configuration = new Imageloaderconfiguration.builder (this). Writedebuglogs ()//print log information. build ();//initialize imageloader with configuration. Imageloader.getinstance (). init (configuration);}}
Let's take a look at the log information that's loaded
The first piece of information. Tell us to start loading pictures, print out the URL of the picture and the maximum width and height of the image, the width of the image is the width of the device, of course, if we are very clear about the size of the picture, we can also go to set this size, In the imageloaderconfiguration option memorycacheextraoptions (int maximagewidthformemorycache, int Maximageheightformemorycache)
The second message shows that the images we loaded are from the network
The third message shows that the original size of the picture is 682 x 341 after clipping
Fourth display picture added to the memory cache, I did not add to the SD card, so no file cache log
We are loading the web images. There is often a need to display the picture download progress. Universal-image-loader Of course also provides this function, only need to pass the Imageloadingprogresslistener interface in the DisplayImage () method. Code such as the following
Imageloader.displayimage (IMAGEURL, Mimageview, Options, New Simpleimageloadinglistener (), New Imageloadingprogresslistener () {@Overridepublic void Onprogressupdate (String imageuri, view view, int current,int Total ) {}});
Since the method with Imageloadingprogresslistener in the DisplayImage () method has a imageloadinglistener parameter, I am here directly new A simpleimageloadinglistener, and then we can get the loading progress of the image in the callback method Onprogressupdate ().
Images loaded in other sources
Use Universal-image-loader frame not only can load the network picture, also can load the SD card picture, the Content provider and so on, the use is also very easy, only is the picture URL slightly changes under can, below is the loading file system picture
Displays the configuration of the picture displayimageoptions options = new Displayimageoptions.builder (). showimageonloading (R.drawable.ic_stub). Showimageonfail (R.drawable.ic_error). Cacheinmemory (True). Cacheondisk (True). Bitmapconfig (Bitmap.Config.RGB_565) . build (); final ImageView Mimageview = (ImageView) Findviewbyid (r.id.image); String ImagePath = "/mnt/sdcard/image.png"; String imageUrl = Scheme.FILE.wrap (ImagePath);//string imageUrl = "http://img.my.csdn.net/uploads/201309/01/ 1378037235_7476.jpg "; Imageloader.displayimage (ImageUrl, Mimageview, Options);
And, of course, from the content provider,drawable,assets. It's also very easy to use, and we just need to add scheme packages to each source of the image (except for Content provider). It is then passed to the Imageloader as the URL of the picture. The Universal-image-loader framework gets the input stream based on different scheme
Image from content providerstring Contentprividerurl = "CONTENT://MEDIA/EXTERNAL/AUDIO/ALBUMART/13";// Image from Assetsstring Assetsurl = Scheme.ASSETS.wrap ("Image.png");//image from String drawableurl = Scheme.DRAWABLE.wrap (" R.drawable.image ");
Girdview,listview Loading Pictures
It is believed that most people use Gridview,listview to display a large number of images. And when we slide the GridView at high speed. Listview. We want to stop the loading of the image and load the picture of the current interface when the Gridview,listview stops sliding, which of course also provides this function, which is also very easy to use. It provides pauseonscrolllistener this class to control the Listview,gridview sliding process to stop loading the picture, which uses the proxy mode
Listview.setonscrolllistener (New Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling)); Gridview.setonscrolllistener (New Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling));
The first parameter is our picture loading object Imageloader, and the second one is controlling whether to pause loading the picture during the slide. Suppose you need to pause to pass true, the third parameter controls the hard sliding interface when the picture is loaded
OutOfMemoryError
Although this framework has a very good caching mechanism, effectively avoid the production of oom, generally, the probability of generating oom is relatively small, but there is no guarantee that outofmemoryerror never happen, this framework for OutOfMemoryError do a simple catch, Make sure our program encounters Oom without being crash out. But suppose we use this framework to often happen to oom, how should we improve it?
- Reduce the number of threads in the thread pool. Configured in Imageloaderconfiguration (. threadpoolsize), recommended configuration 1-5
- Configure Bitmapconfig to Bitmap.Config.RGB_565 in the Displayimageoptions option, and rgb_565 will consume twice times less memory than argb_8888 by default because argb_8888 is used.
- The memory cache for the configuration picture in Imageloaderconfiguration is MemoryCache (new Weakmemorycache ()) or does not use a memory cache
- Set the. Imagescaletype (Imagescaletype.in_sample_int) or Imagescaletype (ImageScaleType.EXACTLY) in the displayimageoptions option.
Through these, I believe that the use of Universal-image-loader framework has been very well understood. We try to use the DisplayImage () method to load the picture when using the framework, LoadImage () is the callback of the picture object to the Imageloadinglistener interface Onloadingcomplete () method, We need to set it manually to ImageView. The DisplayImage () method uses the weak references for the ImageView object. Facilitates recycling of ImageView objects by the garbage collector. Let's say we want to load a fixed-size picture. Using the LoadImage () method requires passing a ImageSize object, and the DisplayImage () method is based on the measured value of the ImageView object, or Android:layout_width and Android:layout_ The value set by height. or Android:maxwidth and/or Android:maxheight set the value to crop the picture
Today to everyone to share here, there is no clear place in the following message, I will try to answer for everyone. Next article I will continue to analyze this framework in more depth, I hope you continue to pay attention to.
Android Open Source Framework universal-image-loader (a)---basic introduction and use