Android third party resource use Imagecache

Source: Internet
Author: User
Tags prefetch

Reprint please indicate the source: Wang 亟亟 's way of Daniel

The original author of the reference Library Git:https://github.com/trinea

Now a lot of the view that needs to be presented is used in the H5 and WebView, and some use the traditional asynchronous loading operation, today is written the traditional view implementation (H5 can see this article: http://blog.csdn.net/ddwhan0123/ article/details/49683799)

We commonly used such as Imageloader ,Picasso have similar effect, today is the domestic Daniel Trinea Imagecache, then why use his this?

Personally, he is more lightweight, the effect is simple, some derivative and stretching is also good.

First of all, let's talk about some of the more important points of knowledge. (We do not produce knowledge, we are only the porter of knowledge)

caching : Java object creation requires more time to allocate resources, and the more objects you create, the more frequent the GC affects the system response. Mainly use singleton mode, cache (picture cache, thread pool, view cache, IO cache, message cache, notification bar notification cache) and other ways to reduce object creation.

Then the cache, the picture cache, the thread pool, the view cache, the IO cache, the message cache, the notification bar notification cache, and so on. (This is not our main content, do not know to Google, this is just an example)

So, what are the common asynchronous loading problems in a practical scenario?

A. The line item picture displays duplicates
This display repetition means that the current line item shows a picture of the previous line item.
For example, the ListView slides to the 2nd line to load a picture asynchronously, but the load is slow, the ListView has slid to the 14th row during the loading process, and the picture is loaded at the end of the slide, line 2nd is no longer on the screen, according to the above-mentioned caching principle, the 2nd line view may be re-used by the 14th line , so what we see is that line 14th shows the image that should be on line 2nd, causing the display to repeat.

B. Line item picture shows confusion
This display disorder refers to a line item that shows a picture that does not belong to the line item.
For example, the ListView slides to the 2nd line to load a picture asynchronously, but the load is slow, the ListView has been sliding to the 14th row, the 2nd line is no longer on the screen, according to the caching principle described above, the 2nd line of view may be reused by the 14th line, Line 14th shows the view of line 2nd, when the previous picture is loaded, it will appear in line 14th, causing confusion.

c. Line item picture Display flashes
In the case of the above B, the 14th line of the picture again quickly loaded the end, so we see the 14th line first shows the image of line 2nd, and immediately display their own pictures to cover the flickering confusion

Because, if we use the back key to return to the last activity and then come in again to reload it? Or am I loading locally for the first time and then reading the local IO for the second time? As a result, caching is a great way to improve user experience and save performance.

Two. Imagecache

What advantages does Imagecache have?

(1). Easy to use (2). Easy access to and prefetching of new images (3). Contains a level two cache (4). You can choose from a variety of cache algorithms (FIFO, LIFO, LRU, MRU, LFU, MFU, etc.) or a custom cache algorithm (5). It is easy to save and initialize the recovery data (6). Support file SD card save and custom file name rule (7). Good flow performance (only one thread gets the picture) (8). Support for different types of network processing (9). The cache can be initialized according to the system configuration (10). Strong extensibility (11). Support Waiting Queue (12). Most of the interfaces that contain the map.

-1. Use:

A. Initializing a Imagecache object

publicstaticfinal ImageCache IMAGE_CACHE = CacheManager.getImageCache();

B. Call the Get (String imageUrl, view view) to load the picture asynchronously where the picture needs to be loaded

IMAGE_CACHE.get(imageUrl, imageView);

is spicy simple, the effect can be achieved.

Of course, a series of requirements, such as caching, threading, and so on, can also be set:

/** Image Cache **/ Public Static FinalImagecache Image_cache =NewImagecache ();Static{Onimagecallbacklistener Imagecallback =NewOnimagecallbacklistener () {Private Static Final LongSerialversionuid =1L//callback function before get image, run on UI thread        @Override         Public void Onpreget(String imageUrl, view view) {//LOG.E (Tag_cache, "Pre get Image");}//callback function after get image successfully, run on UI thread        @Override         Public void ongetsuccess(String imageUrl, Bitmap loadedimage, view view,BooleanIsincache) {//Can be another view child, like TextView and so on            if(View! =NULL&& Loadedimage! =NULL&& ViewinstanceofImageView) {ImageView ImageView = (ImageView) view;            Imageview.setimagebitmap (Loadedimage); }        }//callback function after get image failed, run on UI thread        @Override         Public void ongetfailed(String imageUrl, Bitmap loadedimage, view view, Failedreason Failedreason) {LOG.E (Tag_cache,NewStringBuilder ( -). Append ("Get Image"). Append (IMAGEURL). Append ("Error"). ToString ()); }@Override         Public void Ongetnotincache(String imageUrl, view view)    {        }    }; Image_cache.setonimagecallbacklistener (imagecallback);}

-2. function

(1) Multiple constructors to initialize the cache according to the configuration of the system
Public Imagecache ()
Public Imagecache (int primarycachemaxsize)
Public Imagecache (int primarycachemaxsize, int secondarycachemaxsize)
Public Imagecache (int primarycachemaxsize, int primarycachethreadpoolsize, int secondarycachemaxsize, int Secondarycachethreadpoolsize)
Supports four constructors, supports level one and level two cache sizes, and gets the settings for the size of the image thread pool. By default, the cache size is set based on the system available memory size, and the thread pool size is set based on the number of system CPUs.

(2), get pictures and automatic prefetch
Get (String imageUrl, view view) asynchronously gets the picture, automatically calls Onimagecallbacklistener's ongetsuccess function after the picture gets successful, returns whether it is already in the cache
Get (String imageUrl, List urllist, view view) asynchronously gets the picture, and automatically calls Onimagecallbacklistener's ongetsuccess function after the picture gets successful. And, based on the position of the ImageUrl in Urllist, prefetch the picture forward and back, returns whether it is already in the cache.

public void Setforwardcachenumber (int forwardcachenumber) to prefetch the number of pictures forward, default to Preloaddatacache#default_forward_cache_ Number
public void Setbackwardcachenumber (int backwardcachenumber) sets default to the number of backward prefetch pictures, default to Preloaddatacache#default_backward_ Cache_number

Public CacheObject get (K key)
Public CacheObject get (K key, List keylist)
Two interfaces are directly synchronized to get the picture, and the ongetsuccess function of Onimagecallbacklistener will not be called when the success is obtained

(3), set cache algorithm
Setcachefullremovetype (Cachefullremovetype cachefullremovetype)
Sets the cache algorithm, which is the rule for deleting old data in order to insert new data when the cache is full.

Currently includes FIFO, LIFO, LRU, MRU, LFU, MFU, priority low first Delete, priority high first delete, data small first delete, data big first Delete, picture small first delete, picture big first Delete, never delete. You can also customize the cache algorithm by implementing Cachefullremovetype: The default is Removetypeusedcountsmall, which is to remove the LRU using low frequency first. Each algorithm is described in detail below:
Removetypeentertimefirst FIFO first out, first go first delete
Removetypeentertimelast LIFO LIFO, after entry first delete
Removetypelastusedtimefirst LRU (Least recently user), first use delete first
Removetypelastusedtimelast MRU (most recently used), recently used first delete
Removetypeusedcountsmall LFU (Least frequently used), first removed with low frequency
Removetypeusedcountbig MRU (most frequently used), first removed with high frequency
Removetypeprioritylow Priority Low First delete
Removetypepriorityhigh Priority Low First delete
Removetypebitmapsmall a small picture first delete
Removetypebitmaplarge The big picture first delete
Removetypedatabig data is deleted first, depending on the CompareTo function of the cached data
Removetypedatasmall data is deleted first, depending on the CompareTo function of the cached data
Removetypenotremove is not deleted, no new data is allowed to be inserted when the cache is full

The custom caching algorithm only needs to implement the Cachefullremovetype compare method. A comparison of less than 0 indicates that the result is deleted first

 Public  class Removetypepriorityhigh<T> implements Cachefullremovetype <T> {    Private Static Final LongSerialversionuid =1L @Override Public intCompare (cacheobject<t> obj1, cacheobject<t> obj2) {return(Obj2.getpriority () > Obj1.getpriority ())?1: ((obj2.getpriority () = = Obj1.getpriority ())?0: -1); }}

(4), Save and initialize recovery data
public Boolean Savedatatodb (context context, String tag)
Save the data to the database, can be called when the program exits, not recommended when each activity ondestrory, but the entire program exit (such as "Exit confirmation Dialog" Click Confirmation), see this Article 3.1 frequently asked questions.
public void InitData (context context, String tag)
Initialization of the recovery data, can be called at the beginning of the loading of the program, not recommended in each activity OnCreate call, but the entire program initialization (such as application OnCreate function), see this Article 3.1 frequently asked questions.

(5), whether the queue is enabled
Setopenwaitingqueue (Boolean Isopenwaitingqueue)
Whether the wait queue is turned on when different view gets the picture through the Get function.
If open, save all the view, the picture gets successful, then call Onimagecallbacklistener's ongetsuccess function, otherwise only the view that last call get is saved, The ongetsuccess function called Onimagecallbacklistener after the picture gets successful
Queue Wait is turned on by default. Set to False if you want optimal performance and the scene is satisfied.

(6), set the Image acquisition method interface
Setongetdatalistener (Ongetdatalistener

setOnGetDataListener(ImageCacheManager.getImageFromSdcardListener());

Note that this method Compresslistener is invalid, if you want to take advantage of Compresslistener, you can set the following:

Setongetdatalistener (NewOngetdatalistener<string, bitmap> () {Private Static Final LongSerialversionuid =1L@Override     PublicCacheobject<bitmap>Ongetdata(String ImagePath) {if(! Fileutils.isfileexist (ImagePath)) {return NULL; } Compresslistener Compresslistener = Image_cache.getcompresslistener ();intCompresssize =0;if(Compresslistener! =NULL) {compresssize = Compresslistener.getcompresssize (ImagePath); } Bitmap BM;if(Compresssize >1) {bitmapfactory.options option =NewBitmapfactory.options ();            Option.insamplesize = compresssize;        BM = bitmapfactory.decodefile (imagePath, option); }Else{BM = Bitmapfactory.decodefile (ImagePath); }return(BM = =NULL?NULL:NewCacheobject<bitmap> (BM)); }});

5. Memory Overflow oom problem?
Compress the picture through the Setcompresslistener interface, getcompresssize the return value to the picture's length-to-width scale, with bitmapfactory.options#insamplesize

23456789Ten One A - - the -Image_cache.setcompresslistener (NewCompresslistener () {@Override     Public int getcompresssize(String ImagePath) {if(Fileutils.isfileexist (ImagePath)) {LongFileSize = Fileutils.getfilesize (imagePath)/ +;/** * If image bigger than 100k, compress to 1/(n + 1) Width and 1/(n + 1) height, n is filesize/100k **/            if(FileSize > -) {return(int) (FileSize/ -) +1; }        }return 1; }});

Also visible picture OutOfMemory exception bitmap size exceeds VM budget reasons and solutions

More content can be found in the author's documentation.

Next, we'll stick to our sample code:

Package directory:

Source Address: Https://github.com/ddwhan0123/BlogSample/tree/master/ImageCacheDemo

Thanks to the audience, sir.

Android third party resource use Imagecache

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.