Android Development Imageloader Local Cache _android

Source: Internet
Author: User
Tags garbage collection save file

Imageloader is a picture cache of open Source Library, provides a powerful image caching mechanism, many developers are using, today to introduce the Android development of the Imageloader local cache, the details are as follows:

Local caching provides two ways to modify file names when caching files, each of which corresponds to a Java class

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

2) Md5filenamegenerator, this class saves the name of the source file after it has been MD5 encrypted.

All two classes inherit the Filenamegenerator interface

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

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


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

The file Getfiledectory () returns the disk cache root
file get (string Imageuri) to obtain a picture
Boolean save (string Imageuri from the cache, based on the URI. InputStream Iamgestream,ioutils.copylistener Listener) Save the picture on the disk cache
Boolean save (String imageuri,bitmap Bitmap) Save Bitmap object to disk cache
Boolean remove (Imageuri) to remove file
void Close () by Imageuri to turn off disk caching, freeing resource
void clear () emptying the disk cache

It then defines another interface diskcache that does not have a method, and the interface simply inherits the Disccacheaware interface.

Basedisccache implements the DiskCache, which is an abstract class that defines the following properties of a disk buffer :

1 The default cache size is 32k

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

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

Provides a set method that modifies the format and compression of compressed pictures and modifies the cache size. The class also encapsulates the following three properties

Protected final file cachedir;//cache file save directory
protected final file reservecachedir;//fallback cache diectory, When Cachedir does not exist, it is using the Reservecahcedir fallback cache
protected final filenamegenerator filenamegenerator;//filename name Builder


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 The constructor of only one parameter initializes only the Cachedir, does not use the fallback cache, and is the file name of the target file generated in Hashcodefilenamegenerator.

2 The constructor of two parameters 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 the filennamegenerator must be initialized otherwise it is 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 {//Get Imageuri F 
Ile object that encapsulates the cache path and the name of the picture save File imagefile = GetFile (Imageuri); 
Gets the Tmpfile object of the temporary save file, 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 Temfile if (savedsuccessfully &&!tmpfile.renameto (imagefile)) {If the save succeeds and the Tempfile file is not successfully moved to ImageFile 
Savedsuccessfully = false; 
} if (!savedsuccessfully) {tmpfile.delete (); 
}///Bitmap garbage collection bitmap.recycle (); 
return savedsuccessfully; }

Basedisccache has two extended classes, one that does not limit the cache size Unlimiteddisccache and the limitedagedisccache that limit cache time. Where Unlimiteddisccache is simple it simply inherits the Basedisccache and does not make any extensions to Basedisccache.

Limitedagedisccache This class implements the deletion of files that are loaded over a specified time in the cache: deleting files from the cache when the following conditions are met: System Current time-file update time > Maxfileage


This class provides two properties:

1. Maxfileage (long) sets the maximum time of the load timeout, the change time in the constructor flush initialization, once initialization can not be changed (set file to survive the longest time, when this value, delete the file)

2. Loadingdates (map<file,long>), which is a Map-type object, the key holds the image file to be cached, and value saves the call Save method is the current time of the system. The concrete padding data to loadingdates is implemented in the following Rememberusage method, which is called in the two save methods in the class, first calling the parent class's Save method, 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 for fetching data from the cache is get (String Imageuri), which is the overridden Basediscdache method that obtains the most recent update time loadingdate of the picture represented by Imageuri from Loadingdates. Then take the current time and loadingdate do bad, if the difference is greater than maxfileage that is, check the maximum time to load, delete the file represented by the Imageuri, and from the loadingdates data, Of course, if there is no imageuri in the map does not involve the timeout problem, at this time put 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; 

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.