Android-universal-image-loader is an open source project that handles loading and caching of images. Leisure time to read some of the source code, special records.
Say the picture file (disk) cache, you need to consider the following factors
1) Definition of the name of the cache file
2) Size of the cache
3) How to cache files: such as limited-time saving files, image Compression format, compression rate and so on.
The project also supports changes to the file name when the file is saved to the disk cache: There are two ways to modify the file name when the file is cached, each of which 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 are as shown
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 ();}
Here's a specific implementation of the disk cache:
The Disccacheaware interface is defined first, and the interface provides the following methods
|
Method name |
Description |
return value |
|
Getfiledectory () |
Returns the root directory of the disk cache |
File |
|
Get (String Imageuri) |
according to 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 according to Imageuri |
Boolean |
|
Close () |
Turn off the disk cache and release resources |
void |
|
Clear () |
Emptying the disk cache |
void |
And then define another no method interface DiskCache (this interface name should be named Disccache better), the interface is simply inherited 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 rewrite all the methods provided by the 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 (as the first parameter of the Compress method for bitmap)
3) The quality of the image display after the default compression is 100, that is, the compression rate is 0, does not compress (as the second parameter of compress)
Of course, this class also provides a set method to modify the compressed picture format and compression rate, and to modify the cache size. 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;//filename name Generator when Cachedir is not present
The class provides three constructors
1) Only one parameter of the constructor initializes the Cachedir, does not use the fallback cache, and is the file name of the target file that is generated with hashcodefilenamegenerator.
2) Two-parameter constructors can initialize the fallback cache in addition to Cachedir and Hashcodefilenamegenerator
3) The constructor for three parameters requires that Cachedir must be initialized and Filennamegenerator must be initialized or otherwise reported as an exception
The code for the three constructors is as follows
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 each file object of Cachedir.listfiles () and then calls 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 as follows (this method also has a call 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) Specific 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 temporary save files 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);//delete Temfileif (savedsuccessfully & If Save succeeds and Tempfile file is not successfully moved to ImageFile) &!tmpfile.renameto (ImageFile)) {savedsuccessfully = false;} if (!savedsuccessfully) {tmpfile.delete ();}} Garbage collection of bitmap bitmap.recycle (); return savedsuccessfully;}
5) Another way to handle the overload of Save is the same as the logic above, it should be noted that the two save method when the file is saved will be a tempfile and then call the Renameto method to rename the Tempfile to ImageFile
Basedisccache has two extension classes, One is to not limit the cache size of the Unlimiteddisccache and limit the cache time Limitedagedisccache where Unlimiteddisccache is simple it simply inherits Basedisccache did not do any expansion of Basedisccache Show.
Limitedagedisccache This class implements the deletion of files in the cache that have been loaded for more than the specified time: Delete files from the cache when the following conditions are met: System Current time-the last modified time of the file Maxfileage
The class provides two properties:
1. Maxfileage (long) sets the maximum time for the load timeout to be initialized in the constructor, and cannot be changed once initialized (the maximum time to set the file to survive, and delete the file when 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 specific padding of the data to Loadingdates is 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 the overriding Basediscdache method, which gets the latest update time loadingdate for the picture represented by Imageuri from Loadingdates, Then take the current time and loadingdate do poor, if the difference is greater than maxfileage that is to check the maximum time to load, delete the Imageuri represented by the file, and from the loadingdates data, Of course, if there is no imageuri in the map will not involve the problem of timeouts, at this point, the image into the map, the specific implementation of 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;}