Android--Imageloader local cache

Source: Internet
Author: User
Tags md5 encryption

Transmission Door

"Android-Imageloader Analysis" http://www.cnblogs.com/yydcdut/p/4008097.html

Local Cache

There are two ways to modify file names when caching files, 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

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

 Public Static filenamegenerator Createfilenamegenerator () {          returnnew  Hashcodefilenamegenerator ();      }
Implement

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

    • File getfiledectory () returns the root directory of the disk cache
    • File get (String Imageuri) Gets the picture from the cache based on the URI
    • Boolean Save (String imageuri,inputstream Iamgestream,ioutils.copylistener Listener) to save the picture on the disk cache
    • Boolean Save (String imageuri,bitmap Bitmap) Saves the Bitmap object to the disk cache
    • Boolean remove (Imageuri) deletes files based on Imageuri
    • void Close () Close the disk cache and release resources
    • void Clear () empties the disk cache

Then we define another interface diskcache that has no method, which simply inherits the Disccacheaware interface.

Basedisccache implements the DiskCache, which is an abstract class that defines the following 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)

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

 protected  final  File cachedir;< Span style= "color: #008000;" >//  save directory for cache files  protected  Span style= "color: #0000ff;" >final  File Reservecachedir; //  Diectory of the fallback cache, when Cachedir is not present, uses Reservecahcedir fallback cache  protected  final  Filenamegenerator Filenamegenerator; //  filename name Generator  
constructor Function
 PublicBasedisccache (File cachedir) { This(Cachedir,NULL); } Publicbasedisccache (file cachedir, file Reservecachedir) { This(Cachedir, Reservecachedir, Defaultconfigurationfactory.createfilenamegenerator ()); } Publicbasedisccache (file cachedir, file Reservecachedir, Filenamegenerator filenamegenerator) {if(Cachedir = =NULL) {            Throw NewIllegalArgumentException ("Cachedir" +error_arg_null); }        if(Filenamegenerator = =NULL) {            Throw NewIllegalArgumentException ("Filenamegenerator" +error_arg_null); }         This. Cachedir =Cachedir;  This. Reservecachedir =Reservecachedir;  This. Filenamegenerator =Filenamegenerator; }

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

get (String Imageuri)
 protected   File GetFile (String Imageuri) {          String fileName  = Filenamegenerator.generate (Imageuri);          File dir  = Cachedir;  if  (!cachedir.exists () &&! Cachedir.mkdirs ()) { if  (reservecachedir! = null  && (reservecachedir.exists () | |  Reservecachedir.mkdirs ()))              {dir  = Reservecachedir; }}  return  new   File (dir, fileName); }
Save (String Imageuri, Bitmap Bitmap)
 Public BooleanSave (String Imageuri, Bitmap Bitmap)throwsIOException {//gets the file object for the Imageuri, which encapsulates the cache path and the name of the picture after it is savedFile ImageFile =GetFile (Imageuri); //gets the Tmpfile object that temporarily saves the fileFile tmpfile =NewFile (Imagefile.getabsolutepath () +Temp_image_postfix); OutputStream OS=NewBufferedoutputstream (NewFileOutputStream (tmpfile), buffersize); Booleansavedsuccessfully =false; Try {              //call compress to compress the bitmap into Tempfilesavedsuccessfully =bitmap.compress (Compressformat, compressquality, OS); } finally{ioutils.closesilently (OS); //If the save succeeds and the Tempfile file is not successfully moved to ImageFile, delete the Temfile            if(savedsuccessfully &&!)Tmpfile.renameto (ImageFile)) {savedsuccessfully=false; }              if(!savedsuccessfully)              {Tmpfile.delete (); }          }          //garbage collection of bitmapbitmap.recycle (); returnsavedsuccessfully; }

Basedisccache has two extension classes, one is a unlimiteddisccache that does not limit the size of the cache and Limitedagedisccache to limit cache time, Where Unlimiteddisccache is simple it simply inherits the Basedisccache and does not do any extensions to Basedisccache.

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-file last modified time > Maxfileage

Limitedagedisccache

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) {      = 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

@Override Publicfile Get (String imageuri) {File file=Super. Get (Imageuri); if(File! =NULL&&file.exists ()) {              Booleancached; Long loadingdate=loadingdates.get (file); if(Loadingdate = =NULL) {Cached=false; Loadingdate=file.lastmodified (); } Else{Cached=true; }                if(System.currenttimemillis ()-loadingdate >maxfileage)                  {File.delete ();              Loadingdates.remove (file); } Else if(!cached)              {loadingdates.put (file, loadingdate); }          }          returnfile; }
I'm the dividing line of the king of the land Tiger.

Android--Imageloader local cache

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.