Android ImageLoader local cache, androidimageloader

Source: Internet
Author: User

Android ImageLoader local cache, androidimageloader

Android ImageLoader local cache


Local Cache

When caching a file, you can modify the file name in two ways. Each method corresponds to a Java class.

1) HashCodeFileNameGenerator, which 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.

The DefaultConfigurationFactory class provides a factory method createFileNameGenerator, which returns a default FileNameGenerator object: HashCodeFileNameGenerator.

public static FileNameGenerator createFileNameGenerator() {          return new HashCodeFileNameGenerator();      }
Implementation

The DiscCacheAware interface is defined first, which provides the following methods:
File getFileDectory () returns the root directory of the disk cache File get (String imageUri) obtains the image boolean save (String imageUri, InputStream iamgeStream, 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 and release the resource void clear () to clear the disk cache.

Then define another interface DiskCache with no method. This interface simply inherits the DiscCacheAware interface.

BaseDiscCache implements DiskCache, which is an abstract class that 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) by default, after compression, the image display quality is 100, that is, the compression ratio is 0, and no compression is performed (as the second parameter of compress)

It provides a set method to modify the compressed image format and compression ratio, and modify the cache size. This class also encapsulates the following three attributes:

Protected final File cacheDir; // Save the cached File Directoryprotected final File cached; // backup cache diecloud. If cacheDir does not exist, use the protected backup cache protected final FileNameGenerator fileNameGenerator; // file name Generator
Constructor
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 constructor initializes cacheDir and does not use the backup cache. It uses HashCodeFileNameGenerator to generate the object name of the target object.
2) Besides cacheDir and HashCodefileNameGenerator, the constructors of the two parameters can also initialize the backup cache.
3) The constructors of the three parameters must initialize cacheDir and filenNameGenerator; otherwise, an exception is reported.
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 the File object of imageUri, 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 bytes = false; try {// call compress to compress bitMap to tempFi In le, savedSuccessfully = 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 ;}

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, but it simply inherits BaseDiscCache and does not perform any extension on basediscc.

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

This class 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 rememberUsage(String imageUri) {      File file = getFile(imageUri);      long currentTime = System.currentTimeMillis();      file.setLastModified(currentTime);      loadingDates.put(file, currentTime);  }
The method for obtaining 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, the current time and loadingDate are used as the difference. If the difference is greater than maxFileAge, that is, the maximum loading time is checked, the file represented by the imageUri is deleted and the data in loadingDates is retrieved, of course, if map does not have imageUri, it will not involve timeout. In this case, the image will be placed in map. The specific implementation is as follows:

@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

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.