Android-universal-image-loader Study notes (one)

Source: Internet
Author: User

Android-universal-image-loader It is an open source project that handles image loading and caching. In your spare time, read some sources. Special Records.

The image file (disk) cache, we need to consider factors such as the following

1) Define the name of the cache file

2) Size of the cache

3) How to cache files: Save files for example. The format after which the picture is compressed. Compression rate and so on.

The project also supports changes to file names when the disk cache is saved: There are two ways to change file names when caching files. Each way corresponds to a Java class

1) Hashcodefilenamegenerator, which is responsible for obtaining the hashcode of the file name and then converting it into a string.

2) Md5filenamegenerator, this class is the name of the source file with the MD5 encryption after the save.

Two classes inherit the Filenamegenerator interface

The relationships between them, such as those seen in the

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvy2h1bnfpdxdlaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

A factory method Createfilenamegenerator is provided in the Defaultconfigurationfactory class. The method returns a default Filenamegenerator object: Hashcodefilenamegenerator.

public static Filenamegenerator Createfilenamegenerator () {return new Hashcodefilenamegenerator ();}

The following is a detailed implementation of the disk cache:

The Disccacheaware interface is defined first, and the interface provides examples such as the following methods

Method name

Description

return value

Getfiledectory ()

Returns the root folder of the disk cache

File

Get (String Imageuri)

based on URI get a picture from the cache

File

Save (imageuri,inputstream Iamgestream,ioutils.copylistener Listener)

Save the picture on the disk cache

Boolean

Save (Imageuri,bitmap Bitmap)

Save the Bitmap object to the disk cache

Boolean

Remove (Imageuri)

Delete files based on Imageuri

Boolean

Close ()

Turn off the disk cache and release resources

void

Clear ()

Emptying the disk cache

void

And then define another interface without a method DiskCache (this interface name should be named Disccache better). The interface is simply inherited from the Disccacheaware interface.

Basedisccache implements DiskCache, which is an abstract class (one of the benefits of defining an abstract class is that it is not necessary to have all of the methods provided by the overriding Diskcacheaware interface), which defines the following (default) properties of the disk buffers:

1) The default cache size is 32k

2) The default compressed picture format is PNG (the first parameter as the Compress method of the bitmap)

3) The image display quality is 100 after the default compression, that is, the compression rate is 0, does not compress (as a second parameter of compress)

Of course, this class also provides a set method that changes the format and compression ratio of compressed images and changes the size of the cache.

At the same time, the class also encapsulates the following three properties

The protected final file cachedir;//cache file is saved directoryprotected the final file reservecachedir;//the diectory of the fallback cache, Reservecahcedir fallback cache protected final filenamegenerator filenamegenerator;//file name Generator when Cachedir is not present

The class provides three constructors

1) Only one parameter constructor initializes the Cachedir. No utility to the fallback cache. and is the file name of the Hashcodefilenamegenerator to generate the target file.

2) Two-parameter constructors can initialize the fallback cache in addition to Cachedir and Hashcodefilenamegenerator

3) The constructor for three parameters requires that the Cachedir must be initialized and must be initialized filennamegenerator otherwise it will be reported as an exception

Code for three constructors such as the following

Public Basedisccache (File cachedir) {This (cachedir, null);} Public Basedisccache (file Cachedir, file Reservecachedir) {This (Cachedir, Reservecachedir, Defaultconfigurationfactory.createfilenamegenerator ());} Public Basedisccache (file Cachedir, file Reservecachedir, Filenamegenerator filenamegenerator) {if (Cachedir = = null) {th Row new IllegalArgumentException ("Cachedir" + Error_arg_null);} if (Filenamegenerator = = null) {throw new IllegalArgumentException ("Filenamegenerator" + Error_arg_null);} This.cachedir = Cachedir;this.reservecachedir = Reservecachedir;this.filenamegenerator = FileNameGenerator;}

The Basicdisccache implements the remaining six methods except close, which are described in one by one below:

1) Clear (): Loop facilitates cachedir.listfiles () for each file object. Then call the file object's Delete () method to empty the cache

2) Getdirectory (): Returned directly to the Cachedir

3) Get (Stringimageuri): This method calls an important method of Basiccahce GetFile (String imageuri).

The method is seen in the following example (this method is also called in the Save method)

Protected File GetFile (String imageuri) {string fileName = Filenamegenerator.generate (Imageuri); File dir = cachedir;if (!cachedir.exists () &&!cachedir.mkdirs ()) {if (Reservecachedir! = null && (Reserve Cachedir.exists () | | Reservecachedir.mkdirs ())) {dir = Reservecachedir;}} return new File (dir, fileName);}

4) Detailed implementation of the Save (Stringimageuri, Bitmap Bitmap) method

Public boolean Save (String Imageuri, Bitmap Bitmap) throws IOException {//Gets the Imageuri file object that encapsulates the cache path and the name after the picture is saved file ImageFile = GetFile (Imageuri);//Gets the Tmpfile object for the temporary save file Tmpfile = new file (Imagefile.getabsolutepath () + Temp_image_ POSTFIX); OutputStream os = new Bufferedoutputstream (new FileOutputStream (tmpfile), buffersize); Boolean savedsuccessfully = false;try {//Call compress to compress bitmap into tempfile savedsuccessfully = bitmap.compress (Compressformat, compressquality, OS);} finally {ioutils.closesilently (OS);//Assuming the save succeeds and Tempfile file is not successfully moved to ImageFile. Delete Temfileif (savedsuccessfully &&!tmpfile.renameto (imagefile)) {savedsuccessfully = false;} if (!savedsuccessfully) {tmpfile.delete ();}} Garbage collection of bitmap bitmap.recycle (); return savedsuccessfully;}

5) Save for another overloaded method to handle the logic above, it should be noted that the two save method when the file is saved will be a tempfile and then will call the Renameto method to rename the Tempfile to ImageFile

Basedisccache has two extension classes, One is not limit the size of the cache Unlimiteddisccache and limit the cache time Limitedagedisccache Unlimiteddisccache very easy it is simply inherited Basedisccache did not basedisccache Do whatever extension.

Limitedagedisccache This class implements the deletion of files in the cache that are loaded beyond the specified time: Delete files from the cache when the following conditions are met: Current time of the system-the latest time to change the file maxfileage

The class provides two properties:

1. Maxfileage (long) sets the maximum time to load the timeout, changing the time in the constructor flush initialization. Cannot be changed once initialized (sets the maximum time the file survives, and deletes the file if it exceeds this value)

2. Loadingdates (map<file,long>), which is a Map type object, key holds the picture file to be cached, and value holds the current time for the system to call the Save method. The details of populating the loadingdates with data are implemented in the following Rememberusage method, which is called in two save methods in the class, first calling the Save method of the parent class, and then calling this method

private void Rememberusage (String imageuri) {File File = GetFile (Imageuri); Long currenttime = System.currenttimemillis () ; file.setlastmodified (currenttime); loadingdates.put (file, currenttime);}

The method of fetching data from the cache is get (String Imageuri) that class is overriding the Basediscdache method. This method obtains the latest update time loadingdate of the picture represented by Imageuri from Loadingdates, and then takes the current time and loadingdate to do worse. Assuming that the difference is greater than maxfileage, which means that the maximum time to load is checked, delete the file represented by the Imageuri and the data from the loadingdates. Of course, if there is no imageuri in the map will not involve the problem of time-out, at this point, the image into the map, detailed implementation such as the following

@Overridepublic file Get (String imageuri) {File File = Super.get (Imageuri); if (File! = null && file.exists ()) {Boo Lean cached; Long loadingdate = loadingdates.get (file), if (loadingdate = = null) {cached = False;loadingdate = File.lastmodified ();} els e {cached = true;} if (System.currenttimemillis ()-loadingdate > Maxfileage) {file.delete (); loadingdates.remove (file);} else if (! Cached) {loadingdates.put (file, loadingdate);}} return file;}





Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Android-universal-image-loader Study notes (one)

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.