阿里云服务器免费领卷啦。

捡代码论坛-最全的游戏源码下载技术网站!

 找回密码
 立 即 注 册

QQ登录

只需一步,快速开始

搜索
关于源码区的附件失效或欺骗帖, 处理办法
查看: 2884|回复: 0

Android之本地缓存——LruCache(内存缓存)与DiskLruCache(硬...

[复制链接]

4208

主题

210

回帖

12万

积分

管理员

管理员

Rank: 9Rank: 9Rank: 9

积分
126222
QQ
发表于 2016-7-6 12:39:46 | 显示全部楼层 |阅读模式
Android之本地缓存——LruCache(内存缓存)与DiskLruCache(硬盘缓存)统一框架

本文参考郭霖大神的DiskLruCache解析,感兴趣的朋友可以先到http://blog.csdn.net/guolin_blog/article/details/28863651了解。

一、前言

该框架或者说库,主要是用于本地的图片缓存处理。

数据的存入

当你取到图片的元数据,会将数据存入硬盘缓存以及内存缓存中。

数据的获取

取数据的时候,先从内存缓存中取;

如果没有取到,则从硬盘缓存中取(此时如果硬盘缓存有数据,硬盘缓存会重新将数据写入内存缓存中);

如果硬盘缓存中没有取到,则从网上重新获取元数据;

二、设计

根据以上提到的功能:

首先,我们对LruCache以及DiskLruCache分别做了一个管理类,分别命名为LruCacheManager、DiskLruCacheManager,类中对用户可能用到的方法做封装;

其次,需要一个统一管理来CacheManager,对LruCacheManager、DiskLruCacheManager中的方法做调度;

三、具体实现1、内存缓存管理——LruCacheManager

先贴代码,有个直观认识:

  1. package com.utils.cache;

  2. import android.graphics.Bitmap;
  3. import android.support.v4.util.LruCache;

  4. public class LruCacheManager {
  5.    
  6.         private LruCache<String, Bitmap> lruCache;
  7.         public LruCacheManager(){
  8.                 this((int)Runtime.getRuntime().maxMemory()/1024/8);
  9.         }
  10.         //设置自定义大小的LruCache
  11.         public LruCacheManager(int maxSize){
  12.                 lruCache=new LruCache<String, Bitmap>(maxSize*1024){

  13.                         @Override
  14.                         protected int sizeOf(String key, Bitmap value) {
  15.                                 return value.getByteCount()/1024;
  16.                         }
  17.                        
  18.                 };
  19.         }
  20.     /**
  21.      * 写入索引key对应的缓存
  22.      * @param key 索引
  23.      * @param bitmap 缓存内容
  24.      * @return 写入结果
  25.      */
  26.         public Bitmap putCache(String key,Bitmap bitmap){
  27.                 Bitmap bitmapValue=getCache(key);
  28.                 if(bitmapValue==null){
  29.                         if(lruCache!=null&&bitmap!=null)
  30.                         bitmapValue= lruCache.put(key, bitmap);
  31.                 }
  32.                 return bitmapValue;
  33.         }
  34.         /**
  35.          * 获取缓存
  36.          * @param key 索引key对应的缓存
  37.          * @return  缓存
  38.          */
  39.         public Bitmap getCache(String key){
  40.                 if(lruCache!=null){
  41.                         return lruCache.get(key);
  42.                 }
  43.                 return null;
  44.         }
  45.        
  46.         public void deleteCache(){
  47.                 if(lruCache!=null)
  48.                 lruCache.evictAll();
  49.         }
  50.        
  51.         public void removeCache(String key){
  52.                 if(lruCache!=null)
  53.                 lruCache.remove(key);
  54.         }
  55.        
  56.         public int size(){
  57.                 int size=0;
  58.                 if(lruCache!=null)
  59.                         size+=lruCache.size();
  60.                 return size;
  61.         }
  62. }
复制代码

该类是依赖于Android提供的LruCache类实现的。


在该类中,提供了两个构造方法,默认的构造方法是给内存缓存分配当前Android操作系统分配给该app的内存的1/8。这话比较拗口,意识就是,如果操作系统分配给app的内存是96M,那么默认构造方法就是给内存缓存分配内存96/8M。另一个构造方法是让用户自定义内存缓存大小。

该类中其他的方法就不多做解释,都是对LruCache方法的一次封装。

2、硬盘缓存管理——DiskLruCacheManager

使用硬盘缓存管理前,需要先下载一个开源类:DiskLruCache,如下:

  1. /*
  2. * Copyright (C) 2011 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. *      http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */

  16. package com.utils.cache;

  17. import java.io.BufferedInputStream;
  18. import java.io.BufferedWriter;
  19. import java.io.Closeable;
  20. import java.io.EOFException;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.FileNotFoundException;
  24. import java.io.FileOutputStream;
  25. import java.io.FileWriter;
  26. import java.io.FilterOutputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.InputStreamReader;
  30. import java.io.OutputStream;
  31. import java.io.OutputStreamWriter;
  32. import java.io.Reader;
  33. import java.io.StringWriter;
  34. import java.io.Writer;
  35. import java.lang.reflect.Array;
  36. import java.nio.charset.Charset;
  37. import java.util.ArrayList;
  38. import java.util.Arrays;
  39. import java.util.Iterator;
  40. import java.util.LinkedHashMap;
  41. import java.util.Map;
  42. import java.util.concurrent.Callable;
  43. import java.util.concurrent.ExecutorService;
  44. import java.util.concurrent.LinkedBlockingQueue;
  45. import java.util.concurrent.ThreadPoolExecutor;
  46. import java.util.concurrent.TimeUnit;

  47. /**
  48. ******************************************************************************
  49. * Taken from the JB source code, can be found in:
  50. * libcore/luni/src/main/java/libcore/io/DiskLruCache.java
  51. * or direct link:
  52. * https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java
  53. ******************************************************************************
  54. *
  55. * A cache that uses a bounded amount of space on a filesystem. Each cache
  56. * entry has a string key and a fixed number of values. Values are byte
  57. * sequences, accessible as streams or files. Each value must be between {@code
  58. * 0} and {@code Integer.MAX_VALUE} bytes in length.
  59. *
  60. * <p>The cache stores its data in a directory on the filesystem. This
  61. * directory must be exclusive to the cache; the cache may delete or overwrite
  62. * files from its directory. It is an error for multiple processes to use the
  63. * same cache directory at the same time.
  64. *
  65. * <p>This cache limits the number of bytes that it will store on the
  66. * filesystem. When the number of stored bytes exceeds the limit, the cache will
  67. * remove entries in the background until the limit is satisfied. The limit is
  68. * not strict: the cache may temporarily exceed it while waiting for files to be
  69. * deleted. The limit does not include filesystem overhead or the cache
  70. * journal so space-sensitive applications should set a conservative limit.
  71. *
  72. * <p>Clients call {@link #edit} to create or update the values of an entry. An
  73. * entry may have only one editor at one time; if a value is not available to be
  74. * edited then {@link #edit} will return null.
  75. * <ul>
  76. *     <li>When an entry is being <strong>created</strong> it is necessary to
  77. *         supply a full set of values; the empty value should be used as a
  78. *         placeholder if necessary.
  79. *     <li>When an entry is being <strong>edited</strong>, it is not necessary
  80. *         to supply data for every value; values default to their previous
  81. *         value.
  82. * </ul>
  83. * Every {@link #edit} call must be matched by a call to {@link Editor#commit}
  84. * or {@link Editor#abort}. Committing is atomic: a read observes the full set
  85. * of values as they were before or after the commit, but never a mix of values.
  86. *
  87. * <p>Clients call {@link #get} to read a snapshot of an entry. The read will
  88. * observe the value at the time that {@link #get} was called. Updates and
  89. * removals after the call do not impact ongoing reads.
  90. *
  91. * <p>This class is tolerant of some I/O errors. If files are missing from the
  92. * filesystem, the corresponding entries will be dropped from the cache. If
  93. * an error occurs while writing a cache value, the edit will fail silently.
  94. * Callers should handle other problems by catching {@code IOException} and
  95. * responding appropriately.
  96. */
  97. public final class DiskLruCache implements Closeable {
  98.     static final String JOURNAL_FILE = "journal";
  99.     static final String JOURNAL_FILE_TMP = "journal.tmp";
  100.     static final String MAGIC = "libcore.io.DiskLruCache";
  101.     static final String VERSION_1 = "1";
  102.     static final long ANY_SEQUENCE_NUMBER = -1;
  103.     private static final String CLEAN = "CLEAN";
  104.     private static final String DIRTY = "DIRTY";
  105.     private static final String REMOVE = "REMOVE";
  106.     private static final String READ = "READ";

  107.     private static final Charset UTF_8 = Charset.forName("UTF-8");
  108.     private static final int IO_BUFFER_SIZE = 8 * 1024;

  109.     /*
  110.      * This cache uses a journal file named "journal". A typical journal file
  111.      * looks like this:
  112.      *     libcore.io.DiskLruCache
  113.      *     1
  114.      *     100
  115.      *     2
  116.      *
  117.      *     CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
  118.      *     DIRTY 335c4c6028171cfddfbaae1a9c313c52
  119.      *     CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
  120.      *     REMOVE 335c4c6028171cfddfbaae1a9c313c52
  121.      *     DIRTY 1ab96a171faeeee38496d8b330771a7a
  122.      *     CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
  123.      *     READ 335c4c6028171cfddfbaae1a9c313c52
  124.      *     READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
  125.      *
  126.      * The first five lines of the journal form its header. They are the
  127.      * constant string "libcore.io.DiskLruCache", the disk cache's version,
  128.      * the application's version, the value count, and a blank line.
  129.      *
  130.      * Each of the subsequent lines in the file is a record of the state of a
  131.      * cache entry. Each line contains space-separated values: a state, a key,
  132.      * and optional state-specific values.
  133.      *   o DIRTY lines track that an entry is actively being created or updated.
  134.      *     Every successful DIRTY action should be followed by a CLEAN or REMOVE
  135.      *     action. DIRTY lines without a matching CLEAN or REMOVE indicate that
  136.      *     temporary files may need to be deleted.
  137.      *   o CLEAN lines track a cache entry that has been successfully published
  138.      *     and may be read. A publish line is followed by the lengths of each of
  139.      *     its values.
  140.      *   o READ lines track accesses for LRU.
  141.      *   o REMOVE lines track entries that have been deleted.
  142.      *
  143.      * The journal file is appended to as cache operations occur. The journal may
  144.      * occasionally be compacted by dropping redundant lines. A temporary file named
  145.      * "journal.tmp" will be used during compaction; that file should be deleted if
  146.      * it exists when the cache is opened.
  147.      */

  148.     private final File directory;
  149.     private final File journalFile;
  150.     private final File journalFileTmp;
  151.     private final int appVersion;
  152.     private final long maxSize;
  153.     private final int valueCount;
  154.     private long size = 0;
  155.     private Writer journalWriter;
  156.     private final LinkedHashMap<String, Entry> lruEntries
  157.             = new LinkedHashMap<String, Entry>(0, 0.75f, true);
  158.     private int redundantOpCount;

  159.     /**
  160.      * To differentiate between old and current snapshots, each entry is given
  161.      * a sequence number each time an edit is committed. A snapshot is stale if
  162.      * its sequence number is not equal to its entry's sequence number.
  163.      */
  164.     private long nextSequenceNumber = 0;

  165.     /* From java.util.Arrays */
  166.     @SuppressWarnings("unchecked")
  167.     private static <T> T[] copyOfRange(T[] original, int start, int end) {
  168.         final int originalLength = original.length; // For exception priority compatibility.
  169.         if (start > end) {
  170.             throw new IllegalArgumentException();
  171.         }
  172.         if (start < 0 || start > originalLength) {
  173.             throw new ArrayIndexOutOfBoundsException();
  174.         }
  175.         final int resultLength = end - start;
  176.         final int copyLength = Math.min(resultLength, originalLength - start);
  177.         final T[] result = (T[]) Array
  178.                 .newInstance(original.getClass().getComponentType(), resultLength);
  179.         System.arraycopy(original, start, result, 0, copyLength);
  180.         return result;
  181.     }

  182.     /**
  183.      * Returns the remainder of 'reader' as a string, closing it when done.
  184.      */
  185.     public static String readFully(Reader reader) throws IOException {
  186.         try {
  187.             StringWriter writer = new StringWriter();
  188.             char[] buffer = new char[1024];
  189.             int count;
  190.             while ((count = reader.read(buffer)) != -1) {
  191.                 writer.write(buffer, 0, count);
  192.             }
  193.             return writer.toString();
  194.         } finally {
  195.             reader.close();
  196.         }
  197.     }

  198.     /**
  199.      * Returns the ASCII characters up to but not including the next "\r\n", or
  200.      * "\n".
  201.      *
  202.      * @throws java.io.EOFException if the stream is exhausted before the next newline
  203.      *     character.
  204.      */
  205.     public static String readAsciiLine(InputStream in) throws IOException {
  206.         // TODO: support UTF-8 here instead

  207.         StringBuilder result = new StringBuilder(80);
  208.         while (true) {
  209.             int c = in.read();
  210.             if (c == -1) {
  211.                 throw new EOFException();
  212.             } else if (c == '\n') {
  213.                 break;
  214.             }

  215.             result.append((char) c);
  216.         }
  217.         int length = result.length();
  218.         if (length > 0 && result.charAt(length - 1) == '\r') {
  219.             result.setLength(length - 1);
  220.         }
  221.         return result.toString();
  222.     }

  223.     /**
  224.      * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
  225.      */
  226.     public static void closeQuietly(Closeable closeable) {
  227.         if (closeable != null) {
  228.             try {
  229.                 closeable.close();
  230.             } catch (RuntimeException rethrown) {
  231.                 throw rethrown;
  232.             } catch (Exception ignored) {
  233.             }
  234.         }
  235.     }

  236.     /**
  237.      * Recursively delete everything in {@code dir}.
  238.      */
  239.     // TODO: this should specify paths as Strings rather than as Files
  240.     public static void deleteContents(File dir) throws IOException {
  241.         File[] files = dir.listFiles();
  242.         if (files == null) {
  243.             throw new IllegalArgumentException("not a directory: " + dir);
  244.         }
  245.         for (File file : files) {
  246.             if (file.isDirectory()) {
  247.                 deleteContents(file);
  248.             }
  249.             if (!file.delete()) {
  250.                 throw new IOException("failed to delete file: " + file);
  251.             }
  252.         }
  253.     }

  254.     /** This cache uses a single background thread to evict entries. */
  255.     private final ExecutorService executorService = new ThreadPoolExecutor(0, 1,
  256.             60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
  257.     private final Callable<Void> cleanupCallable = new Callable<Void>() {
  258.         @Override public Void call() throws Exception {
  259.             synchronized (DiskLruCache.this) {
  260.                 if (journalWriter == null) {
  261.                     return null; // closed
  262.                 }
  263.                 trimToSize();
  264.                 if (journalRebuildRequired()) {
  265.                     rebuildJournal();
  266.                     redundantOpCount = 0;
  267.                 }
  268.             }
  269.             return null;
  270.         }
  271.     };

  272.     private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
  273.         this.directory = directory;
  274.         this.appVersion = appVersion;
  275.         this.journalFile = new File(directory, JOURNAL_FILE);
  276.         this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP);
  277.         this.valueCount = valueCount;
  278.         this.maxSize = maxSize;
  279.     }

  280.     /**
  281.      * Opens the cache in {@code directory}, creating a cache if none exists
  282.      * there.
  283.      *
  284.      * @param directory a writable directory
  285.      * @param appVersion
  286.      * @param valueCount the number of values per cache entry. Must be positive.
  287.      * @param maxSize the maximum number of bytes this cache should use to store
  288.      * @throws java.io.IOException if reading or writing the cache directory fails
  289.      */
  290.     public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
  291.             throws IOException {
  292.         if (maxSize <= 0) {
  293.             throw new IllegalArgumentException("maxSize <= 0");
  294.         }
  295.         if (valueCount <= 0) {
  296.             throw new IllegalArgumentException("valueCount <= 0");
  297.         }

  298.         // prefer to pick up where we left off
  299.         DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
  300.         if (cache.journalFile.exists()) {
  301.             try {
  302.                 cache.readJournal();
  303.                 cache.processJournal();
  304.                 cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true),
  305.                         IO_BUFFER_SIZE);
  306.                 return cache;
  307.             } catch (IOException journalIsCorrupt) {
  308. //                System.logW("DiskLruCache " + directory + " is corrupt: "
  309. //                        + journalIsCorrupt.getMessage() + ", removing");
  310.                 cache.delete();
  311.             }
  312.         }

  313.         // create a new empty cache
  314.         directory.mkdirs();
  315.         cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
  316.         cache.rebuildJournal();
  317.         return cache;
  318.     }

  319.     private void readJournal() throws IOException {
  320.         InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
  321.         try {
  322.             String magic = readAsciiLine(in);
  323.             String version = readAsciiLine(in);
  324.             String appVersionString = readAsciiLine(in);
  325.             String valueCountString = readAsciiLine(in);
  326.             String blank = readAsciiLine(in);
  327.             if (!MAGIC.equals(magic)
  328.                     || !VERSION_1.equals(version)
  329.                     || !Integer.toString(appVersion).equals(appVersionString)
  330.                     || !Integer.toString(valueCount).equals(valueCountString)
  331.                     || !"".equals(blank)) {
  332.                 throw new IOException("unexpected journal header: ["
  333.                         + magic + ", " + version + ", " + valueCountString + ", " + blank + "]");
  334.             }

  335.             while (true) {
  336.                 try {
  337.                     readJournalLine(readAsciiLine(in));
  338.                 } catch (EOFException endOfJournal) {
  339.                     break;
  340.                 }
  341.             }
  342.         } finally {
  343.             closeQuietly(in);
  344.         }
  345.     }

  346.     private void readJournalLine(String line) throws IOException {
  347.         String[] parts = line.split(" ");
  348.         if (parts.length < 2) {
  349.             throw new IOException("unexpected journal line: " + line);
  350.         }

  351.         String key = parts[1];
  352.         if (parts[0].equals(REMOVE) && parts.length == 2) {
  353.             lruEntries.remove(key);
  354.             return;
  355.         }

  356.         Entry entry = lruEntries.get(key);
  357.         if (entry == null) {
  358.             entry = new Entry(key);
  359.             lruEntries.put(key, entry);
  360.         }

  361.         if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) {
  362.             entry.readable = true;
  363.             entry.currentEditor = null;
  364.             entry.setLengths(copyOfRange(parts, 2, parts.length));
  365.         } else if (parts[0].equals(DIRTY) && parts.length == 2) {
  366.             entry.currentEditor = new Editor(entry);
  367.         } else if (parts[0].equals(READ) && parts.length == 2) {
  368.             // this work was already done by calling lruEntries.get()
  369.         } else {
  370.             throw new IOException("unexpected journal line: " + line);
  371.         }
  372.     }

  373.     /**
  374.      * Computes the initial size and collects garbage as a part of opening the
  375.      * cache. Dirty entries are assumed to be inconsistent and will be deleted.
  376.      */
  377.     private void processJournal() throws IOException {
  378.         deleteIfExists(journalFileTmp);
  379.         for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
  380.             Entry entry = i.next();
  381.             if (entry.currentEditor == null) {
  382.                 for (int t = 0; t < valueCount; t++) {
  383.                     size += entry.lengths[t];
  384.                 }
  385.             } else {
  386.                 entry.currentEditor = null;
  387.                 for (int t = 0; t < valueCount; t++) {
  388.                     deleteIfExists(entry.getCleanFile(t));
  389.                     deleteIfExists(entry.getDirtyFile(t));
  390.                 }
  391.                 i.remove();
  392.             }
  393.         }
  394.     }

  395.     /**
  396.      * Creates a new journal that omits redundant information. This replaces the
  397.      * current journal if it exists.
  398.      */
  399.     private synchronized void rebuildJournal() throws IOException {
  400.         if (journalWriter != null) {
  401.             journalWriter.close();
  402.         }

  403.         Writer writer = new BufferedWriter(new FileWriter(journalFileTmp), IO_BUFFER_SIZE);
  404.         writer.write(MAGIC);
  405.         writer.write("\n");
  406.         writer.write(VERSION_1);
  407.         writer.write("\n");
  408.         writer.write(Integer.toString(appVersion));
  409.         writer.write("\n");
  410.         writer.write(Integer.toString(valueCount));
  411.         writer.write("\n");
  412.         writer.write("\n");

  413.         for (Entry entry : lruEntries.values()) {
  414.             if (entry.currentEditor != null) {
  415.                 writer.write(DIRTY + ' ' + entry.key + '\n');
  416.             } else {
  417.                 writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
  418.             }
  419.         }

  420.         writer.close();
  421.         journalFileTmp.renameTo(journalFile);
  422.         journalWriter = new BufferedWriter(new FileWriter(journalFile, true), IO_BUFFER_SIZE);
  423.     }

  424.     private static void deleteIfExists(File file) throws IOException {
  425. //        try {
  426. //            Libcore.os.remove(file.getPath());
  427. //        } catch (ErrnoException errnoException) {
  428. //            if (errnoException.errno != OsConstants.ENOENT) {
  429. //                throw errnoException.rethrowAsIOException();
  430. //            }
  431. //        }
  432.         if (file.exists() && !file.delete()) {
  433.             throw new IOException();
  434.         }
  435.     }

  436.     /**
  437.      * Returns a snapshot of the entry named {@code key}, or null if it doesn't
  438.      * exist is not currently readable. If a value is returned, it is moved to
  439.      * the head of the LRU queue.
  440.      */
  441.     public synchronized Snapshot get(String key) throws IOException {
  442.         checkNotClosed();
  443.         validateKey(key);
  444.         Entry entry = lruEntries.get(key);
  445.         if (entry == null) {
  446.             return null;
  447.         }

  448.         if (!entry.readable) {
  449.             return null;
  450.         }

  451.         /*
  452.          * Open all streams eagerly to guarantee that we see a single published
  453.          * snapshot. If we opened streams lazily then the streams could come
  454.          * from different edits.
  455.          */
  456.         InputStream[] ins = new InputStream[valueCount];
  457.         try {
  458.             for (int i = 0; i < valueCount; i++) {
  459.                 ins[i] = new FileInputStream(entry.getCleanFile(i));
  460.             }
  461.         } catch (FileNotFoundException e) {
  462.             // a file must have been deleted manually!
  463.             return null;
  464.         }

  465.         redundantOpCount++;
  466.         journalWriter.append(READ + ' ' + key + '\n');
  467.         if (journalRebuildRequired()) {
  468.             executorService.submit(cleanupCallable);
  469.         }

  470.         return new Snapshot(key, entry.sequenceNumber, ins);
  471.     }

  472.     /**
  473.      * Returns an editor for the entry named {@code key}, or null if another
  474.      * edit is in progress.
  475.      */
  476.     public Editor edit(String key) throws IOException {
  477.         return edit(key, ANY_SEQUENCE_NUMBER);
  478.     }

  479.     private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
  480.         checkNotClosed();
  481.         validateKey(key);
  482.         Entry entry = lruEntries.get(key);
  483.         if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER
  484.                 && (entry == null || entry.sequenceNumber != expectedSequenceNumber)) {
  485.             return null; // snapshot is stale
  486.         }
  487.         if (entry == null) {
  488.             entry = new Entry(key);
  489.             lruEntries.put(key, entry);
  490.         } else if (entry.currentEditor != null) {
  491.             return null; // another edit is in progress
  492.         }

  493.         Editor editor = new Editor(entry);
  494.         entry.currentEditor = editor;

  495.         // flush the journal before creating files to prevent file leaks
  496.         journalWriter.write(DIRTY + ' ' + key + '\n');
  497.         journalWriter.flush();
  498.         return editor;
  499.     }

  500.     /**
  501.      * Returns the directory where this cache stores its data.
  502.      */
  503.     public File getDirectory() {
  504.         return directory;
  505.     }

  506.     /**
  507.      * Returns the maximum number of bytes that this cache should use to store
  508.      * its data.
  509.      */
  510.     public long maxSize() {
  511.         return maxSize;
  512.     }

  513.     /**
  514.      * Returns the number of bytes currently being used to store the values in
  515.      * this cache. This may be greater than the max size if a background
  516.      * deletion is pending.
  517.      */
  518.     public synchronized long size() {
  519.         return size;
  520.     }

  521.     private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
  522.         Entry entry = editor.entry;
  523.         if (entry.currentEditor != editor) {
  524.             throw new IllegalStateException();
  525.         }

  526.         // if this edit is creating the entry for the first time, every index must have a value
  527.         if (success && !entry.readable) {
  528.             for (int i = 0; i < valueCount; i++) {
  529.                 if (!entry.getDirtyFile(i).exists()) {
  530.                     editor.abort();
  531.                     throw new IllegalStateException("edit didn't create file " + i);
  532.                 }
  533.             }
  534.         }

  535.         for (int i = 0; i < valueCount; i++) {
  536.             File dirty = entry.getDirtyFile(i);
  537.             if (success) {
  538.                 if (dirty.exists()) {
  539.                     File clean = entry.getCleanFile(i);
  540.                     dirty.renameTo(clean);
  541.                     long oldLength = entry.lengths[i];
  542.                     long newLength = clean.length();
  543.                     entry.lengths[i] = newLength;
  544.                     size = size - oldLength + newLength;
  545.                 }
  546.             } else {
  547.                 deleteIfExists(dirty);
  548.             }
  549.         }

  550.         redundantOpCount++;
  551.         entry.currentEditor = null;
  552.         if (entry.readable | success) {
  553.             entry.readable = true;
  554.             journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
  555.             if (success) {
  556.                 entry.sequenceNumber = nextSequenceNumber++;
  557.             }
  558.         } else {
  559.             lruEntries.remove(entry.key);
  560.             journalWriter.write(REMOVE + ' ' + entry.key + '\n');
  561.         }

  562.         if (size > maxSize || journalRebuildRequired()) {
  563.             executorService.submit(cleanupCallable);
  564.         }
  565.     }

  566.     /**
  567.      * We only rebuild the journal when it will halve the size of the journal
  568.      * and eliminate at least 2000 ops.
  569.      */
  570.     private boolean journalRebuildRequired() {
  571.         final int REDUNDANT_OP_COMPACT_THRESHOLD = 2000;
  572.         return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD
  573.                 && redundantOpCount >= lruEntries.size();
  574.     }

  575.     /**
  576.      * Drops the entry for {@code key} if it exists and can be removed. Entries
  577.      * actively being edited cannot be removed.
  578.      *
  579.      * @return true if an entry was removed.
  580.      */
  581.     public synchronized boolean remove(String key) throws IOException {
  582.         checkNotClosed();
  583.         validateKey(key);
  584.         Entry entry = lruEntries.get(key);
  585.         if (entry == null || entry.currentEditor != null) {
  586.             return false;
  587.         }

  588.         for (int i = 0; i < valueCount; i++) {
  589.             File file = entry.getCleanFile(i);
  590.             if (!file.delete()) {
  591.                 throw new IOException("failed to delete " + file);
  592.             }
  593.             size -= entry.lengths[i];
  594.             entry.lengths[i] = 0;
  595.         }

  596.         redundantOpCount++;
  597.         journalWriter.append(REMOVE + ' ' + key + '\n');
  598.         lruEntries.remove(key);

  599.         if (journalRebuildRequired()) {
  600.             executorService.submit(cleanupCallable);
  601.         }

  602.         return true;
  603.     }

  604.     /**
  605.      * Returns true if this cache has been closed.
  606.      */
  607.     public boolean isClosed() {
  608.         return journalWriter == null;
  609.     }

  610.     private void checkNotClosed() {
  611.         if (journalWriter == null) {
  612.             throw new IllegalStateException("cache is closed");
  613.         }
  614.     }

  615.     /**
  616.      * Force buffered operations to the filesystem.
  617.      */
  618.     public synchronized void flush() throws IOException {
  619.         checkNotClosed();
  620.         trimToSize();
  621.         journalWriter.flush();
  622.     }

  623.     /**
  624.      * Closes this cache. Stored values will remain on the filesystem.
  625.      */
  626.     public synchronized void close() throws IOException {
  627.         if (journalWriter == null) {
  628.             return; // already closed
  629.         }
  630.         for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
  631.             if (entry.currentEditor != null) {
  632.                 entry.currentEditor.abort();
  633.             }
  634.         }
  635.         trimToSize();
  636.         journalWriter.close();
  637.         journalWriter = null;
  638.     }

  639.     private void trimToSize() throws IOException {
  640.         while (size > maxSize) {
  641. //            Map.Entry<String, Entry> toEvict = lruEntries.eldest();
  642.             final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
  643.             remove(toEvict.getKey());
  644.         }
  645.     }

  646.     /**
  647.      * Closes the cache and deletes all of its stored values. This will delete
  648.      * all files in the cache directory including files that weren't created by
  649.      * the cache.
  650.      */
  651.     public void delete() throws IOException {
  652.         close();
  653.         deleteContents(directory);
  654.     }

  655.     private void validateKey(String key) {
  656.         if (key.contains(" ") || key.contains("\n") || key.contains("\r")) {
  657.             throw new IllegalArgumentException(
  658.                     "keys must not contain spaces or newlines: "" + key + """);
  659.         }
  660.     }

  661.     private static String inputStreamToString(InputStream in) throws IOException {
  662.         return readFully(new InputStreamReader(in, UTF_8));
  663.     }

  664.     /**
  665.      * A snapshot of the values for an entry.
  666.      */
  667.     public final class Snapshot implements Closeable {
  668.         private final String key;
  669.         private final long sequenceNumber;
  670.         private final InputStream[] ins;

  671.         private Snapshot(String key, long sequenceNumber, InputStream[] ins) {
  672.             this.key = key;
  673.             this.sequenceNumber = sequenceNumber;
  674.             this.ins = ins;
  675.         }

  676.         /**
  677.          * Returns an editor for this snapshot's entry, or null if either the
  678.          * entry has changed since this snapshot was created or if another edit
  679.          * is in progress.
  680.          */
  681.         public Editor edit() throws IOException {
  682.             return DiskLruCache.this.edit(key, sequenceNumber);
  683.         }

  684.         /**
  685.          * Returns the unbuffered stream with the value for {@code index}.
  686.          */
  687.         public InputStream getInputStream(int index) {
  688.             return ins[index];
  689.         }

  690.         /**
  691.          * Returns the string value for {@code index}.
  692.          */
  693.         public String getString(int index) throws IOException {
  694.             return inputStreamToString(getInputStream(index));
  695.         }

  696.         @Override public void close() {
  697.             for (InputStream in : ins) {
  698.                 closeQuietly(in);
  699.             }
  700.         }
  701.     }

  702.     /**
  703.      * Edits the values for an entry.
  704.      */
  705.     public final class Editor {
  706.         private final Entry entry;
  707.         private boolean hasErrors;

  708.         private Editor(Entry entry) {
  709.             this.entry = entry;
  710.         }

  711.         /**
  712.          * Returns an unbuffered input stream to read the last committed value,
  713.          * or null if no value has been committed.
  714.          */
  715.         public InputStream newInputStream(int index) throws IOException {
  716.             synchronized (DiskLruCache.this) {
  717.                 if (entry.currentEditor != this) {
  718.                     throw new IllegalStateException();
  719.                 }
  720.                 if (!entry.readable) {
  721.                     return null;
  722.                 }
  723.                 return new FileInputStream(entry.getCleanFile(index));
  724.             }
  725.         }

  726.         /**
  727.          * Returns the last committed value as a string, or null if no value
  728.          * has been committed.
  729.          */
  730.         public String getString(int index) throws IOException {
  731.             InputStream in = newInputStream(index);
  732.             return in != null ? inputStreamToString(in) : null;
  733.         }

  734.         /**
  735.          * Returns a new unbuffered output stream to write the value at
  736.          * {@code index}. If the underlying output stream encounters errors
  737.          * when writing to the filesystem, this edit will be aborted when
  738.          * {@link #commit} is called. The returned output stream does not throw
  739.          * IOExceptions.
  740.          */
  741.         public OutputStream newOutputStream(int index) throws IOException {
  742.             synchronized (DiskLruCache.this) {
  743.                 if (entry.currentEditor != this) {
  744.                     throw new IllegalStateException();
  745.                 }
  746.                 return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index)));
  747.             }
  748.         }

  749.         /**
  750.          * Sets the value at {@code index} to {@code value}.
  751.          */
  752.         public void set(int index, String value) throws IOException {
  753.             Writer writer = null;
  754.             try {
  755.                 writer = new OutputStreamWriter(newOutputStream(index), UTF_8);
  756.                 writer.write(value);
  757.             } finally {
  758.                 closeQuietly(writer);
  759.             }
  760.         }

  761.         /**
  762.          * Commits this edit so it is visible to readers.  This releases the
  763.          * edit lock so another edit may be started on the same key.
  764.          */
  765.         public void commit() throws IOException {
  766.             if (hasErrors) {
  767.                 completeEdit(this, false);
  768.                 remove(entry.key); // the previous entry is stale
  769.             } else {
  770.                 completeEdit(this, true);
  771.             }
  772.         }

  773.         /**
  774.          * Aborts this edit. This releases the edit lock so another edit may be
  775.          * started on the same key.
  776.          */
  777.         public void abort() throws IOException {
  778.             completeEdit(this, false);
  779.         }

  780.         private class FaultHidingOutputStream extends FilterOutputStream {
  781.             private FaultHidingOutputStream(OutputStream out) {
  782.                 super(out);
  783.             }

  784.             @Override public void write(int oneByte) {
  785.                 try {
  786.                     out.write(oneByte);
  787.                 } catch (IOException e) {
  788.                     hasErrors = true;
  789.                 }
  790.             }

  791.             @Override public void write(byte[] buffer, int offset, int length) {
  792.                 try {
  793.                     out.write(buffer, offset, length);
  794.                 } catch (IOException e) {
  795.                     hasErrors = true;
  796.                 }
  797.             }

  798.             @Override public void close() {
  799.                 try {
  800.                     out.close();
  801.                 } catch (IOException e) {
  802.                     hasErrors = true;
  803.                 }
  804.             }

  805.             @Override public void flush() {
  806.                 try {
  807.                     out.flush();
  808.                 } catch (IOException e) {
  809.                     hasErrors = true;
  810.                 }
  811.             }
  812.         }
  813.     }

  814.     private final class Entry {
  815.         private final String key;

  816.         /** Lengths of this entry's files. */
  817.         private final long[] lengths;

  818.         /** True if this entry has ever been published */
  819.         private boolean readable;

  820.         /** The ongoing edit or null if this entry is not being edited. */
  821.         private Editor currentEditor;

  822.         /** The sequence number of the most recently committed edit to this entry. */
  823.         private long sequenceNumber;

  824.         private Entry(String key) {
  825.             this.key = key;
  826.             this.lengths = new long[valueCount];
  827.         }

  828.         public String getLengths() throws IOException {
  829.             StringBuilder result = new StringBuilder();
  830.             for (long size : lengths) {
  831.                 result.append(' ').append(size);
  832.             }
  833.             return result.toString();
  834.         }

  835.         /**
  836.          * Set lengths using decimal numbers like "10123".
  837.          */
  838.         private void setLengths(String[] strings) throws IOException {
  839.             if (strings.length != valueCount) {
  840.                 throw invalidLengths(strings);
  841.             }

  842.             try {
  843.                 for (int i = 0; i < strings.length; i++) {
  844.                     lengths[i] = Long.parseLong(strings[i]);
  845.                 }
  846.             } catch (NumberFormatException e) {
  847.                 throw invalidLengths(strings);
  848.             }
  849.         }

  850.         private IOException invalidLengths(String[] strings) throws IOException {
  851.             throw new IOException("unexpected journal line: " + Arrays.toString(strings));
  852.         }

  853.         public File getCleanFile(int i) {
  854.             return new File(directory, key + "." + i);
  855.         }

  856.         public File getDirtyFile(int i) {
  857.             return new File(directory, key + "." + i + ".tmp");
  858.         }
  859.     }
  860. }
复制代码

对于该类不了解的可以参考文章首行提到的郭霖的博客链接。


针对这个DIskLruCache,也对它做一层封装,也就是我们的DiskLruCacheManager:

  1. package com.utils.cache;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.security.MessageDigest;
  6. import java.security.NoSuchAlgorithmException;

  7. import com.utils.cache.DiskLruCache.Snapshot;

  8. import android.content.Context;
  9. import android.content.pm.PackageInfo;
  10. import android.content.pm.PackageManager.NameNotFoundException;
  11. import android.graphics.Bitmap;
  12. import android.graphics.BitmapFactory;
  13. import android.os.Environment;


  14. public  class DiskLruCacheManager {
  15.   
  16.   private static int maxSize=20*1024*1024;
  17.   private  DiskLruCache mDiskLruCache;
  18.   private final static String defaultName="default";
  19.   
  20.   public DiskLruCacheManager(Context context){
  21.          this(context, defaultName, maxSize);
  22.   }
  23.   public DiskLruCacheManager(Context context,int maxDiskLruCacheSize){
  24.           this(context, defaultName, maxDiskLruCacheSize);
  25.   }
  26.   public DiskLruCacheManager(Context context,String dirName){
  27.         this(context, dirName, maxSize);
  28.   }
  29.   
  30.   public DiskLruCacheManager(Context context,String dirName,int maxDiskLruCacheSize){
  31.           try {
  32.                   mDiskLruCache=DiskLruCache.open(getDiskCacheFile(context,dirName), getAppVersion(context), 1, maxDiskLruCacheSize);
  33.           } catch (IOException e) {
  34.                   e.printStackTrace();
  35.           }
  36.   }
  37.   /**
  38.    * 获取文件夹地址,如果不存在,则创建
  39.    * @param context 上下文
  40.    * @param dirName 文件名
  41.    * @return  File 文件
  42.    */
  43.   private  File getDiskCacheFile(Context context,String dirName){
  44.       File cacheDir=packDiskCacheFile(context,dirName);
  45.       if (!cacheDir.exists()) {  
  46.           cacheDir.mkdirs();  
  47.       }  
  48.       return cacheDir;  
  49.   }
  50.   
  51.   /**
  52.    * 获取文件夹地址
  53.    * @param context 上下文
  54.    * @param dirName 文件名
  55.    * @return File 文件
  56.    */
  57.   private   File packDiskCacheFile(Context context,String dirName){
  58.           String cachePath;  
  59.       if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())  
  60.               || !Environment.isExternalStorageRemovable()) {  
  61.           cachePath = context.getExternalCacheDir().getPath();  
  62.       } else {  
  63.           cachePath = context.getCacheDir().getPath();  
  64.       }  
  65.       return new File(cachePath + File.separator + dirName);  
  66.   }
  67.   
  68.   /**
  69.    * 获取当前应用程序的版本号。
  70.    */  
  71.   private int getAppVersion(Context context) {  
  72.       try {  
  73.           PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),0);  
  74.           return info.versionCode;  
  75.       } catch (NameNotFoundException e) {  
  76.           e.printStackTrace();  
  77.       }  
  78.       return 1;  
  79.   }  
  80.   
  81.   /**
  82.    * 使用MD5算法对传入的key进行加密并返回。
  83.    */  
  84.   private String Md5(String key) {  
  85.       String cacheKey;  
  86.       try {  
  87.           final MessageDigest mDigest = MessageDigest.getInstance("MD5");  
  88.           mDigest.update(key.getBytes());  
  89.           cacheKey = bytesToHexString(mDigest.digest());  
  90.       } catch (NoSuchAlgorithmException e) {  
  91.           cacheKey = String.valueOf(key.hashCode());  
  92.       }  
  93.       return cacheKey;  
  94.   }  
  95.   
  96.   private String bytesToHexString(byte[] bytes) {  
  97.       StringBuilder sb = new StringBuilder();  
  98.       for (int i = 0; i < bytes.length; i++) {  
  99.           String hex = Integer.toHexString(0xFF & bytes[i]);  
  100.           if (hex.length() == 1) {  
  101.               sb.append('0');  
  102.           }  
  103.           sb.append(hex);  
  104.       }  
  105.       return sb.toString();  
  106.   }  
  107.   /**
  108.    * Bitmap格式数据写入到outputstream中
  109.    * @param bm Bitmap数据
  110.    * @param baos outputstream
  111.    * @return outputstream
  112.    */
  113.   private OutputStream Bitmap2OutputStream(Bitmap bm,OutputStream baos) {  
  114.           if(bm!=null){
  115.               bm.compress(Bitmap.CompressFormat.PNG, 100, baos);  
  116.           }
  117.           return baos;
  118.   }  
  119.   
  120.   /**
  121.    * 将缓存记录同步到journal文件中。
  122.    */  
  123.   public void fluchCache() {  
  124.       if (mDiskLruCache != null) {  
  125.           try {  
  126.               mDiskLruCache.flush();  
  127.           } catch (IOException e) {  
  128.               e.printStackTrace();  
  129.           }  
  130.       }  
  131.   }  

  132.   /**
  133.    * 获取硬盘缓存
  134.    * @param key 所有
  135.    * @return Bitmap格式缓存
  136.    */
  137.   public Bitmap getDiskCache(String key){
  138.         String md5Key=Md5(key);
  139.     Bitmap bitmap=null;
  140.         try {
  141.                 if(mDiskLruCache!=null){
  142.                         Snapshot         snapshot = mDiskLruCache.get(md5Key);
  143.                         if(snapshot!=null){
  144.                                 bitmap=BitmapFactory.decodeStream(snapshot.getInputStream(0)) ;       
  145.                         }
  146.                 }
  147.         }
  148.          catch (IOException e) {
  149.                         e.printStackTrace();
  150.                 }
  151.           return bitmap;
  152.   }
  153.   
  154.   /**
  155.    * 设置key对应的缓存
  156.    * @param key 索引
  157.    * @param bitmap Bitmap格式数据
  158.    * @return 是否写入
  159.    */
  160.   public boolean putDiskCache(String key,Bitmap bitmap){
  161.           String md5Key=Md5(key);
  162.           try {
  163.                   if(mDiskLruCache!=null){
  164.                             if(mDiskLruCache.get(md5Key)!=null){
  165.                                     return true;
  166.                             }
  167.                                 DiskLruCache.Editor editor=mDiskLruCache.edit(md5Key);
  168.                                 if(editor!=null){
  169.                                         OutputStream outputStream= editor.newOutputStream(0);
  170.                                         Bitmap2OutputStream(bitmap,outputStream);
  171.                                         if(outputStream!=null){
  172.                                                 editor.commit();
  173.                                                 return true;
  174.                                         }
  175.                                         else {
  176.                                                 editor.abort();
  177.                                                 return false;
  178.                                         }
  179.                                 }
  180.                   }
  181.         } catch (IOException e) {
  182.                 // TODO Auto-generated catch block
  183.                 e.printStackTrace();
  184.         }
  185.           return false;
  186.   }
  187.   
  188.   public void deleteDiskCache(){
  189.           try {
  190.                   if(mDiskLruCache!=null){
  191.                           mDiskLruCache.delete();
  192.                   }
  193.         } catch (IOException e) {
  194.                 // TODO Auto-generated catch block
  195.                 e.printStackTrace();
  196.         }
  197.   }

  198.   public void removeDiskCache(String key){
  199.           if(mDiskLruCache!=null){
  200.                   try {
  201.                         mDiskLruCache.remove(key);
  202.                 } catch (IOException e) {
  203.                         // TODO Auto-generated catch block
  204.                         e.printStackTrace();
  205.                 }
  206.           }
  207.   }
  208.   
  209.   public  void deleteFile(Context context,String dirName){
  210.           try {
  211.                         DiskLruCache.deleteContents(packDiskCacheFile(context,dirName));
  212.                 } catch (IOException e) {
  213.                         // TODO Auto-generated catch block
  214.                         e.printStackTrace();
  215.                 }
  216.   }
  217.   
  218.   public int size(){
  219.           int size=0;
  220.           if(mDiskLruCache!=null){
  221.                   size=(int) mDiskLruCache.size();
  222.           }
  223.           return size;
  224.   }
  225.   
  226.   public void close(){
  227.           if(mDiskLruCache!=null){
  228.                   try {
  229.                         mDiskLruCache.close();
  230.                 } catch (IOException e) {
  231.                         // TODO Auto-generated catch block
  232.                         e.printStackTrace();
  233.                 }
  234.           }
  235.   }
  236.   
  237. }
复制代码

该封装类中包含4个构造函数,主要也是用于用户的自定义,让用户可以使用默认设置,以及自定义硬盘缓存的文件夹名称以及大小。


后续的封装类,是对硬盘缓存的读写、大小、移除等功能的封装。

3、统一的缓存管理类——CacheManager

这个类是对整个缓存的调度类。使用者也只需要接触这个类即可。CacheManager简化了内存缓存与硬盘缓存同时使用时的代码操作。如下:

  1. package com.utils.cache;

  2. import android.content.Context;
  3. import android.graphics.Bitmap;
  4. import android.text.TextUtils;

  5. public class CacheManager {
  6.     /**
  7.      * 只使用内存缓存(LruCache)
  8.      */
  9.         public static final int ONLY_LRU=1;
  10.         /**
  11.          * 只使用硬盘缓存(DiskLruCache)
  12.          */
  13.         public static final int ONLY_DISKLRU=2;
  14.         /**
  15.          * 同时使用内存缓存(LruCache)与硬盘缓存(DiskLruCache)
  16.          */
  17.         public static final int ALL_ALLOW=0;
  18.        
  19.         /**
  20.          * 设置类型为硬盘缓存——用于取硬盘缓存大小
  21.          */
  22.         public static final int DISKSIZE=0;
  23.         /**
  24.          * 设置类型为内存缓存——用于取内存缓存大小
  25.          */
  26.         public static final int MEMORYSIZE=1;
  27.        
  28.         //设置硬盘缓存的最大值,单位为M
  29.         private static int maxSizeForDiskLruCache=0;
  30.         //设置内存缓存的最大值,单位为M
  31.         private static int maxMemoryForLruCache=0;
  32.         //设置自定义的硬盘缓存文件夹名称
  33.         private static String dirNameForDiskLruCache="";
  34.         //记录硬盘缓存与内存缓存起效标志
  35.         private static int model=0;
  36.         //硬盘缓存管理类
  37.         private static DiskLruCacheManager diskLruCacheManager;
  38.         //内存缓存管理类
  39.         private static LruCacheManager lruCacheManager;
  40.         private static Context ct;
  41.         /**
  42.          * 初始化缓存管理
  43.          * @param context 上下文
  44.          */
  45.         public static void init(Context context){
  46.                 ct=context;
  47.                 init_();
  48.         }
  49.         //根据传入的标志,初始化内存缓存以及硬盘缓存,默认开启是同时使用
  50.         private static void init_(){
  51.                 switch (model) {
  52.                 case ALL_ALLOW:
  53.                         initDiskLruCacheManager();
  54.                         initLruCacheManager();
  55.                         break;
  56.                 case ONLY_LRU:
  57.                         initLruCacheManager();
  58.                         break;
  59.                 case ONLY_DISKLRU:
  60.                         initDiskLruCacheManager();
  61.                         break;
  62.                 default:
  63.                         break;
  64.                 }
  65.         }
  66.         //初始化内存缓存管理
  67.         private static void initLruCacheManager(){
  68.                 if(maxMemoryForLruCache>0){
  69.                         lruCacheManager=new LruCacheManager(maxMemoryForLruCache);
  70.                 }else {
  71.                         lruCacheManager=new LruCacheManager();
  72.                 }
  73.         }
  74.         //初始化硬盘缓存管理
  75.         private static void initDiskLruCacheManager(){
  76.                 if(maxSizeForDiskLruCache>0&&!TextUtils.isEmpty(dirNameForDiskLruCache)){
  77.                          diskLruCacheManager=new DiskLruCacheManager(ct,dirNameForDiskLruCache,maxSizeForDiskLruCache*1024*1024);
  78.                 }else if(maxSizeForDiskLruCache>0){
  79.                         diskLruCacheManager=new DiskLruCacheManager(ct, maxSizeForDiskLruCache*1024*1024);
  80.                 }else if(!TextUtils.isEmpty(dirNameForDiskLruCache)){
  81.                         diskLruCacheManager=new DiskLruCacheManager(ct, dirNameForDiskLruCache);
  82.                 }else {
  83.                         diskLruCacheManager=new DiskLruCacheManager(ct);
  84.                 }
  85.         }
  86.         /**
  87.          * 设置硬盘缓存的最大值,单位为兆(M).
  88.          * @param maxSizeForDisk 硬盘缓存最大值,单位为兆(M)
  89.          */
  90.         public static void setMaxSize(int maxSizeForDisk){
  91.                 maxSizeForDiskLruCache=maxSizeForDisk;
  92.         }
  93.         /**
  94.          * 设置内存缓存的最大值,单位为兆(M).
  95.          * @param maxMemory 内存缓存最大值,单位为兆(M)
  96.          */
  97.         public static void setMaxMemory(int maxMemory){
  98.                 maxMemoryForLruCache=maxMemory;
  99.         }
  100.         /**
  101.          * 设置硬盘缓存自定义的文件名
  102.          * @param dirName 自定义文件名
  103.          */
  104.         public static void setDirName(String dirName){
  105.                 dirNameForDiskLruCache=dirName;
  106.         }
  107.         /**
  108.          * 索引key对应的bitmap写入缓存
  109.          * @param key 缓存索引
  110.          * @param bitmap bitmap格式数据
  111.          */
  112.         public static void put(String key,Bitmap bitmap){
  113.                 switch (model) {
  114.                 case ALL_ALLOW:
  115.                         if(lruCacheManager!=null&&diskLruCacheManager!=null){
  116.                                 //设置硬盘缓存成功后,再设置内存缓存
  117.                                 if(diskLruCacheManager.putDiskCache(key,bitmap)){
  118.                                         lruCacheManager.putCache(key, bitmap);
  119.                                 }
  120.                         }
  121.                         break;
  122.                 case ONLY_LRU:
  123.                         if(lruCacheManager!=null){
  124.                                 lruCacheManager.putCache(key, bitmap);
  125.                         }
  126.                         break;
  127.                 case ONLY_DISKLRU:
  128.                         if(diskLruCacheManager!=null){
  129.                                 diskLruCacheManager.putDiskCache(key,bitmap);
  130.                         }
  131.                         break;
  132.                 default:
  133.                         break;
  134.                 }
  135.         }
  136.        
  137.         /**
  138.          * 获取索引key对应的缓存内容
  139.          * @param key 缓存索引key
  140.          * @return  key索引对应的Bitmap数据
  141.          */
  142.         public static Bitmap get(String key){
  143.                 Bitmap bitmap=null;
  144.                 switch (model) {
  145.                 case ALL_ALLOW:
  146.                         if(lruCacheManager!=null&&diskLruCacheManager!=null){
  147.                                  bitmap=lruCacheManager.getCache(key);
  148.                                 if(bitmap==null){
  149.                                         //如果硬盘缓存内容存在,内存缓存不存在。则在获取硬盘缓存后,将内容写入内存缓存
  150.                                         bitmap=diskLruCacheManager.getDiskCache(key);
  151.                                         lruCacheManager.putCache(key, bitmap);
  152.                                 }
  153.                         }
  154.                         break;
  155.                 case ONLY_LRU:
  156.                         if(lruCacheManager!=null){
  157.                                  bitmap=lruCacheManager.getCache(key);
  158.                         }
  159.                         break;
  160.                 case ONLY_DISKLRU:
  161.                         if(diskLruCacheManager!=null){
  162.                                  bitmap=diskLruCacheManager.getDiskCache(key);
  163.                         }
  164.                         break;

  165.                 default:
  166.                         break;
  167.                 }
  168.                 return bitmap;
  169.         }
  170.         /**
  171.          * 删除所有缓存
  172.          */
  173.         public static void delete(){
  174.                 switch (model) {
  175.                 case ALL_ALLOW:
  176.                         if(lruCacheManager!=null&&diskLruCacheManager!=null){
  177.                                 lruCacheManager.deleteCache();
  178.                                 diskLruCacheManager.deleteDiskCache();
  179.                         }
  180.                         break;
  181.                 case ONLY_LRU:
  182.                         if(lruCacheManager!=null){
  183.                                 lruCacheManager.deleteCache();
  184.                         }
  185.                         break;
  186.                 case ONLY_DISKLRU:
  187.                         if(diskLruCacheManager!=null){
  188.                                 diskLruCacheManager.deleteDiskCache();
  189.                         }
  190.                         break;

  191.                 default:
  192.                         break;
  193.                 }
  194.         }
  195.        
  196.         /**
  197.          * 移除一条索引key对应的缓存
  198.          * @param key 索引
  199.          */
  200.         public  static void remove(String key){
  201.                 switch (model) {
  202.                 case ALL_ALLOW:
  203.                         if(lruCacheManager!=null&&diskLruCacheManager!=null){
  204.                                 lruCacheManager.removeCache(key);
  205.                                 diskLruCacheManager.removeDiskCache(key);
  206.                         }
  207.                         break;
  208.                 case ONLY_LRU:
  209.                         if(lruCacheManager!=null){
  210.                                 lruCacheManager.removeCache(key);
  211.                         }
  212.                         break;
  213.                 case ONLY_DISKLRU:
  214.                         if(diskLruCacheManager!=null){
  215.                                 diskLruCacheManager.removeDiskCache(key);
  216.                         }
  217.                         break;

  218.                 default:
  219.                         break;
  220.                 }
  221.         }
  222.         /**
  223.          * 缓存数据同步
  224.          */
  225.         public static void flush(){
  226.                 switch (model) {
  227.                 case ALL_ALLOW:
  228.                         if(lruCacheManager!=null&&diskLruCacheManager!=null){
  229.                                 diskLruCacheManager.fluchCache();
  230.                         }
  231.                         break;
  232.                 case ONLY_LRU:
  233.                         break;
  234.                 case ONLY_DISKLRU:
  235.                         if(diskLruCacheManager!=null){
  236.                                 diskLruCacheManager.fluchCache();
  237.                         }
  238.                         break;
  239.                 default:
  240.                         break;
  241.                 }
  242.         }
  243.         /**
  244.          * 设置缓存模式
  245.          * @param modelSet ONLY_LRU、ONLY_DISK、ALL_ALLOW
  246.          */
  247.         public static void setCacheModel(int modelSet){
  248.                 model=modelSet;
  249.         }
  250.     /**
  251.      * 删除特定文件名的缓存文件
  252.      * @param dirName 文件名
  253.      */
  254.         public static void deleteFile(String dirName){
  255.                 if(diskLruCacheManager!=null){
  256.                         diskLruCacheManager.deleteFile(ct, dirName);
  257.                 }
  258.         }
  259.         /**
  260.          * 获取缓存大小——内存缓存+硬盘缓存
  261.          * @return
  262.          */
  263.         public static int size(){
  264.                 int size=0;
  265.                 if(diskLruCacheManager!=null){
  266.                         size+=diskLruCacheManager.size();
  267.                 }
  268.                 if(lruCacheManager!=null){
  269.                         size+=lruCacheManager.size();
  270.                 }
  271.                 return size;
  272.         }
  273.         /**
  274.          * 获取缓存大小
  275.          * @param type 硬盘缓存类型:DISKSIZE、内存缓存类型:MEMORYSIZE
  276.          * @return  对应类型的缓存大小
  277.          */
  278.         public static int size(int type){
  279.                 int size=0;
  280.                 switch (type) {
  281.                 case DISKSIZE:
  282.                         if(diskLruCacheManager!=null){
  283.                                 size+=diskLruCacheManager.size();
  284.                         }
  285.                         break;
  286.                 case MEMORYSIZE:
  287.                         if(lruCacheManager!=null){
  288.                                 size+=lruCacheManager.size();
  289.                         }
  290.                         break;

  291.                 default:
  292.                         break;
  293.                 }
  294.                 return size;
  295.         }
  296.         /**
  297.          * 关闭缓存
  298.          */
  299.         public static void close(){
  300.                 if(diskLruCacheManager!=null){
  301.                         diskLruCacheManager.close();
  302.                 }
  303.         }
  304. }
复制代码

各方法在代码中都有详细注释。


简单的说,在使用时,如果使用默认的设置(默认情况下,内存缓存与硬盘缓存同时开启),只需要以下几句简单代码即可实现:

你首先需要初始化:CacheManager.init(Context context);

当你需要设置缓存的时候:CacheManager.put(String key,Bitmap bitmap);

当你需要获取缓存的时候:CacheManager.get(String key);

最后:你可以在这个基础上,添加一些其他你需要的方法,如果缓存文本、字符串等。

四、源码

github上eclipse版本:https://github.com/yangzhaomuma/CacheManager

csdn上android studio版本:http://download.csdn.net/detail/yangzhaomuma/9565578







捡代码论坛-最全的游戏源码下载技术网站! - 论坛版权郑重声明:
1、本主题所有言论和图片纯属会员个人意见,与本论坛立场无关
2、本站所有主题由该帖子作者发表,该帖子作者与捡代码论坛-最全的游戏源码下载技术网站!享有帖子相关版权
3、捡代码论坛版权,详细了解请点击。
4、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。
5、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。 我们不承担任何技术及版权问题,且不对任何资源负法律责任。
6、如无法链接失效或侵犯版权,请给我们来信:jiandaima@foxmail.com

回复

使用道具 举报

*滑块验证:
您需要登录后才可以回帖 登录 | 立 即 注 册

本版积分规则

技术支持
在线咨询
QQ咨询
3351529868

QQ|手机版|小黑屋|捡代码论坛-专业源码分享下载 ( 陕ICP备15015195号-1|网站地图

GMT+8, 2024-5-9 09:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表