Android -- ImageLoader local cache

Source: Internet
Author: User

Android -- ImageLoader local cache
The local cache provides two methods for modifying the file name when caching the file. Each method corresponds to a Java class 1) HashCodeFileNameGenerator, this class obtains the hashcode of the file name and converts it to a string. 2) Md5FileNameGenerator, which encrypts the source file name with md5 and saves it. Both classes inherit the FileNameGenerator interface and provide a factory method createFileNameGenerator in the DefaultConfigurationFactory class. This method returns a default FileNameGenerator object: HashCodeFileNameGenerator. public static FileNameGenerator createFileNameGenerator () {return new HashCodeFileNameGenerator ();} first defines the DiscCacheAware interface, which provides the following method: File getFileDectory () return the disk cache root directory File get (String imageUri) obtain the image boolean save (String imageUri, InputStream iam) from the cache according to the uri GeStream, IoUtils. copyListener listener) save the image to the disk cache boolean save (String imageUri, Bitmap bitmap) save the bitmap object to the disk cache boolean remove (imageUri) delete the file void close () According to imageUri () disable the disk cache, release the resource void clear (), clear the disk cache, and define another interface DiskCache that does not work. This interface simply inherits the DiscCacheAware interface. BaseDiscCache implements DiskCache, which is an abstract class and defines the following attributes of the disk Buffer: 1) the default cache size is 32 KB. 2) by default, the compressed image format is PNG (as the first parameter of the compress method of Bitmap). 3) after compression, the image quality is 100, that is, the compression rate is 0, without compression (as the second parameter of compress), you can set the format and compression ratio of the compressed image and modify the cache size. This class also encapsulates the following three attributes: protected final File cacheDir; // Save the cached File Directoryprotected final File reserveCacheDir; // backup cache diecdir, when cacheDir does not exist, it uses the reserveCahceDir backup cache protected final FileNameGenerator fileNameGenerator; // the File name generator constructor to copy the code public BaseDiscCache (File cacheDir );} public BaseDiscCache (File cacheDir, File reserveCacheDir) {this (cacheDir, reserveCacheDir, DefaultConfigurationFac Invalid. condition ();} public BaseDiscCache (File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator) {if (cacheDir = null) {throw new condition ("cacheDir" + ERROR_ARG_NULL );} if (fileNameGenerator = null) {throw new IllegalArgumentException ("fileNameGenerator" + ERROR_ARG_NULL);} this. cacheDir = cacheDir; this. reserveCacheDir = reserveCacheDir; th Is. fileNameGenerator = fileNameGenerator;} copy code 1) only one constructor of the parameter initializes cacheDir and does not use the backup cache. In addition, HashCodeFileNameGenerator is used to generate the file name of the target file. 2) Besides cacheDir and HashCodefileNameGenerator, the constructors of the two parameters can also initialize the backup cache. 3) the constructor of the three parameters requires that cacheDir be initialized and filenNameGenerator be initialized; otherwise, an exception get (String imageUri) is reported. Copy the Code 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);} copy the code save (String imageUri, Bitmap bitmap) copy the public boolean save (String imageUri, Bitmap bitmap) throws IOException {// obtain the imageUri File object, this object encapsulates the cache path and the saved image name File imageFile = getFile (imageUri); // gets the tmpFile object 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 upload = bitmap. compress (compressFormat, compressQuality, OS);} finally {IoUtils. closeSilently (OS); // Delete the temFile if (savedSuccessfully &&! TmpFile. renameTo (imageFile) {savedSuccessfully = false;} if (! SavedSuccessfully) {tmpFile. delete () ;}// recycle bitmap. recycle (); return savedSuccessfully;} the duplicate code BaseDiscCache has two extension classes. One is the UnlimitedDiscCache that does not limit the cache size and the LimitedAgeDiscCache that limits the cache time, unlimitedDiscCache is simple. It simply inherits BaseDiscCache and does not extend BaseDiscCache. The LimitedAgeDiscCache class allows you to delete files that have been loaded for more than a specified time in the cache: delete files from the cache when the following conditions are met: current System Time-Latest file modification time> maxFileAge LimitedAgeDiscCache provides two attributes: 1. maxFileAge (long) sets the maximum loading time-out period. The modification time is in the initialization of the constructor. Once initialized, it cannot be changed (set the maximum file survival time. When this value is exceeded, delete the file.) 2. loadingDates (Map <File, long>). This attribute is a map-type object. The key stores the image files to be cached, value stores the current time when the save method is called. Specifically, filling in data to loadingDates is implemented in the rememberUsage method below. This method is called in the two save methods in the class, first, call the save method of the parent class, and then call this method private void remembe RUsage (String imageUri) {File file = getFile (imageUri); long currentTime = System. currentTimeMillis (); file. setLastModified (currentTime); loadingDates. put (file, currentTime);} The method for getting data from the cache is get (String imageUri). This class is used to override the BaseDiscDache method, this method obtains the latest update time loadingDate of the image represented by imageUri from loadingDates, and returns the difference between the current time and loadingDate. If the difference is greater than maxFileAge, the maximum loading time is checked, delete the file represented by the imageUri and extract the data from loadingDates. Of course, if the map does not contain the imageUri In this case, the image is put into the map. The specific implementation is as follows: copy the code @ Override public File get (String imageUri) {File 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

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.