Android Universal Imageloader Cache Picture _android

Source: Internet
Author: User

Project Introduction:

One of the biggest headaches on Android is getting pictures, displays, recycling from the web, and any problem with a link may be directly oom, and this project may help you. The purpose of Universal Image Loader for Android is to implement asynchronous network image loading, caching, and display to support multi-threaded asynchronous loading. It was originally derived from the Fedor Vlasov project and has since been reconstructed and improved on a large scale.

Attribute list:

Multi-threaded download pictures, pictures can come from network, file system, project folder assets and drawable medium
Supports random configuration imageloader, such as thread pool, picture downloader, memory cache policy, HDD caching policy, picture display options, and other configurations
Support picture memory cache, file system cache or SD card cache
Support the monitoring of picture downloading process
Crop the bitmap based on the size of the control (ImageView), reducing bitmap memory consumption
Better control of the image loading process, such as suspend picture loading, restart loading pictures, generally used in Listview,gridview, the slide process to suspend loading pictures, stop sliding when to load pictures
Provides loading of pictures on slower networks

Use process:

Create the default Imageloader, all operations are controlled by the Imageloader. This class uses a single example design pattern, so if you want to gain the strength of the class, you need to call the GetInstance () method. Before using Imageloader to display a picture, you first initialize its configuration, call the Imageloaderconfiguration init () method, and then you can implement various displays.

Creates a default Imageloader configuration parameter 
imageloaderconfiguration configuration = imageloaderconfiguration 
. Createdefault ( this); 
Initialize imageloader with configuration. 

Custom configuration Imageloader, as you already know, first, you need to use the Imageloaderconfiguration object to initialize the Imageloader. Since Imageloader is a single case, it is only necessary to initialize the program at the beginning. It is recommended that you initialize the OnCreate () method of the activity. If a imageloader has already been initialized, initializing it again will not have any effect. Below we create a setting through Imageloaderconfiguration.builder

File Cachedir =storageutils.getowncachedirectory (This, "Imageloader/cache"); Imageloaderconfigurationconfig = new Imageloaderconfiguration. Builder (this). Memorycacheextraoptions//MaxWidth, max height, which is the maximum length of each cached file saved. ThreadPoolSize (3)// Number of lines Cheng Chinega loaded. ThreadPriority (thread.norm_priority-2). Denycacheimagemultiplesizesinmemory (). MemoryCache (New Usingfreqlimitedmemorycache (2* 1024 * 1024))//Your can pass your own the cache memory you can implement it through your own memory caches. implementation/ Achesize (2 * 1024 * 1024). disccachesize (1024 * 1024). Disccachefilenamegenerator (())//when will be saved The URI name you designate is encrypted with MD5. Tasksprocessingorder (Queueprocessingtype.lifo). Disccachefilecount (100)//cached number of files. Disccache (new Unlimiteddisccache (Cachedir))//Custom cache path. Defaultdisplayimageoptions (Displayimageoptions.createsimple ()). Imagedownloader (New Baseimagedownloader (this,5 * 1000, 1000))//ConnectTimeout (5 s), ReadTimeout (s) timeout. Write Debuglogs ()//Remove for Releaseapp. Build ();/start building imageloader.getinstance (). init (config);  

Get Imageloader

 
 

Use process:

(1) Whether the image operation participates in caching and the configuration operation of the image effect

Displayimageoptions options = new Displayimageoptions.builder () 
. showimageonloading (r.drawable.ic_stub)// Picture when loading picture 
. Showimageforemptyuri (r.drawable.ic_empty)//default picture when there is no picture resource 
. Showimageonfail (R.drawable.ic_error ////////////////////////////////////////////////// 
cacheinmemory 
Enables EXIF and JPEG image formats 
. Displayer (New Roundedbitmapdisplayer (20))//Set display style This is a rounded rectangle. 

Displayimageoptions The following are all default configuration parameters you can customize the configuration according to the requirements

private int imageresonloading = 0; 
private int imageresforemptyuri = 0; 
private int imageresonfail = 0; 
Private drawable imageonloading = null; 
Private drawable Imageforemptyuri = null; 
Private drawable imageonfail = null; 
Private Boolean resetviewbeforeloading = false; 
Private Boolean cacheinmemory = false; 
Private Boolean cacheondisk = false; 
Private Imagescaletype imagescaletype = imagescaletype.in_sample_power_of_2; 
Private Options Decodingoptions = new options (); 
private int delaybeforeloading = 0; 
Private Boolean considerexifparams = false; 
Private Object extrafordownloader = null; 
Private bitmapprocessor preprocessor = null; 
Private Bitmapprocessor postprocessor = null; 
Private Bitmapdisplayer Displayer = Defaultconfigurationfactory.createbitmapdisplayer (); 
Private Handler Handler = null; 

(2) Picture loading listener Here you can set the animation or progress bar when loading something like this here

Imageloadinglistener Animatefirstlistener = new Animatefirstdisplaylistener (); 
private static class Animatefirstdisplaylistener extends Simpleimageloadinglistener { 
static final list<string > displayedimages = collections.synchronizedlist (New linkedlist<string> ()); 
@Override public 
void Onloadingcomplete (String imageuri, view view, Bitmap loadedimage) { 
if (loadedimage!= null ) { 
ImageView ImageView = (imageview) view; 
Boolean firstdisplay =!displayedimages.contains (Imageuri); 
if (firstdisplay) { 
fadeinbitmapdisplayer.animate (imageview); 
Displayedimages.add (Imageuri);}}} 

(3) Simple settings can add a picture to ImageView

 
 

For a local picture, add "file://" before its absolute address. The network picture is written directly to the path.

Since my this is the latest package, may be different from the old version, see some netizens say is:

String Imageuri = "yun_qi_img/"; Network Picture 
String Imageuri = "File:///mnt/sdcard/image.png";//sd card picture 
string Imageuri = "content://media/external/ AUDIO/ALBUMART/13 "; Media folder 
String Imageuri = "assets://image.png";//Assets 

Cache cleanup:

Cache cleanup can be determined on demand, and can be ondestroy in the lifecycle function of each activity, and can be individually set up for users to clean up themselves.

@Override public 
void OnDestroy () { 
Super.ondestroy (); 
Imageloader.clearmemorycache (); 
Imageloader.cleardiskcache (); 
}

Girdview,listview Load Picture:

I believe most people use Gridview,listview to display a lot of pictures, and when we slide Gridview,listview quickly, we want to stop the image loading and load the picture of the current interface when Gridview,listview stops sliding. , this framework, of course, provides this functionality and is simple to use, and it provides a Pauseonscrolllistener class to control the Listview,gridview sliding process to stop loading pictures, which use proxy mode

Listview.setonscrolllistener (New Pauseonscrolllistener (Imageloader, Pauseonscroll, pauseonfling)); 

The first parameter is our picture loading object Imageloader, the second is to control whether the picture is suspended during the slide, if you need to pause to pass true, and the third parameter controls the swipe of the sliding interface when the picture is loaded

OutOfMemoryError:

Although this framework has a good caching mechanism, the effective avoidance of oom, the general case of the probability of generating oom is relatively small, but can not guarantee that outofmemoryerror never happen, this framework for the OutOfMemoryError do a simple catch, To ensure that our program encounters Oom without being crash, but if we use the framework often oom, how should we improve?

Reduce the number of thread pool threads, configured in Imageloaderconfiguration (. threadpoolsize), recommended configuration 1-5

Configure Bitmapconfig as Bitmap.Config.RGB_565 in the Displayimageoptions option because the default is argb_8888, and using rgb_565 consumes twice times less memory than using argb_8888

Configure the picture's memory cache as MemoryCache (Newweakmemorycache ()) in imageloaderconfiguration or do not use the memory cache

Set. Imagescaletype (Imagescaletype.in_sample_int) or Imagescaletype (ImageScaleType.EXACTLY) in the displayimageoptions option.

Through these, I believe you have been very understanding of the use of the Universal-image-loader framework, we use the framework as far as possible to use the DisplayImage () method to load the picture, LoadImage () is to recall the picture object to the Onloadingcomplete () method of the Imageloadinglistener interface, which requires us to manually set it to the ImageView above, the DisplayImage () method, For the ImageView object, the weak references is used to facilitate the garbage collector to reclaim ImageView objects, and if we want to load a fixed-size picture, we need to pass a LoadImage object using the ImageSize () method. The DisplayImage () method is based on the measured value of the ImageView object, or the value set by Android:layout_width and Android:layout_height, or Android:maxwidth and/ Or android:maxheight the picture by the value set

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.