Android Imageloader Local Cache

Source: Internet
Author: User

Android Imageloader Local Cache


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 () {          return new hashcodefilenamegenerator ();      }
Realize

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 I Amgestream,ioutils.copylistener listener) Save the picture on the disk cache Boolean save (String imageuri,bitmap Bitmap) Save the Bitmap object to the disk cache Boo Lean Remove (imageuri) Delete file void Close () according to Imageuri to close the disk cache, freeing the resource void clear () to empty 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

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
constructor function
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) {            throw 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;    }
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 boolean Save (String Imageuri, Bitmap Bitmap) throws IOException {//Gets the Imageuri file object that encapsulates the cache path and the name of the picture after it is saved          File ImageFile = GetFile (Imageuri);                    Gets the Tmpfile object of 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, Compre          ssquality, OS);              } finally {ioutils.closesilently (OS); If the save succeeds and the Tempfile file is not successfully moved to ImageFile, delete temfile if (savedsuccessfully &&!tmpfile.renameto (imagefi              Le)) {savedsuccessfully = false;              } if (!savedsuccessfully) {tmpfile.delete ();         }}//Bitmap garbage collection bitmap.recycle (); return savedsuccessfully; }

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

@Override public      file Get (String imageuri) {          File File = Super.get (Imageuri);          if (file = null && file.exists ()) {              Boolean cached;              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);              }          }          return file;      }

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.