修改檔案的最後修改時間
java代碼:
- /**
- * 修改檔案的最後修改時間
- * @param dir
- * @param fileName
- */
- private void updateFileTime(String dir,String fileName) {
- File file = new File(dir,fileName);
- long newModifiedTime =System.currentTimeMillis();
- file.setLastModified(newModifiedTime);
- }
複製代碼
本機快取最佳化
java代碼:
- /**
- *計算儲存目錄下的檔案大小,當檔案總大小大於規定的CACHE_SIZE或者sdcard剩餘空間小於FREE_SD_SPACE_NEEDED_TO_CACHE的規定
- * 那麼刪除40%最近沒有被使用的檔案
- * @param dirPath
- * @param filename
- */
- private void removeCache(String dirPath) {
- File dir = new File(dirPath);
- File[] files = dir.listFiles();
- if (files == null) {
- return;
- }
- int dirSize = 0;
- for (int i = 0; i < files.length;i++) {
- if(files[i].getName().contains(WHOLESALE_CONV)) {
- dirSize += files[i].length();
- }
- }
- if (dirSize > CACHE_SIZE * MB ||FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
- int removeFactor = (int) ((0.4 *files.length) + 1);
- Arrays.sort(files, newFileLastModifSort());
- Log.i(TAG, "Clear some expiredcache files ");
- for (int i = 0; i <removeFactor; i++) {
- if(files[i].getName().contains(WHOLESALE_CONV)) {
- files[i].delete();
- }
- }
- }
- }
- /**
- * 刪除到期檔案
- * @param dirPath
- * @param filename
- */
- private void removeExpiredCache(StringdirPath, String filename) {
- File file = new File(dirPath,filename);
- if (System.currentTimeMillis() -file.lastModified() > mTimeDiff) {
- Log.i(TAG, "Clear some expiredcache files ");
- file.delete();
- }
- }
複製代碼
檔案使用時間排序
java代碼:
- /**
- * TODO 根據檔案的最後修改時間進行排序 *
- */
- classFileLastModifSort implements Comparator<File>{
- public int compare(File arg0, File arg1) {
- if (arg0.lastModified() >arg1.lastModified()) {
- return 1;
- } else if (arg0.lastModified() ==arg1.lastModified()) {
- return 0;
- } else {
- return -1;
- }
- }
- }
複製代碼
記憶體儲存:
在記憶體中儲存的話,只能儲存一定的量,而不能一直往裡面放,需要設定資料的到期時間、LRU等演算法。這裡有一個方法是把常用的資料放到一個緩衝中(A),不常用的放到另外一個緩衝中(B)。當要擷取資料時先從A中去擷取,如果A中不存在那麼再去B中擷取。B中的資料主要是A中LRU出來的資料,這裡的記憶體回收主要針對B記憶體,從而保持A中的資料可以有效被命中。
先定義A緩衝:
java代碼:
- private final HashMap<String, Bitmap>mHardBitmapCache = new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY/ 2, 0.75f, true) {
- @Override
- protected booleanremoveEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
- if (size() >HARD_CACHE_CAPACITY) {
- //當map的size大於30時,把最近不常用的key放到mSoftBitmapCache中,從而保證mHardBitmapCache的效率
- mSoftBitmapCache.put(eldest.getKey(), newSoftReference<Bitmap>(eldest.getValue()));
- return true;
- } else
- return false;
- }
- };
複製代碼
再定於B緩衝:
java代碼:
- /**
- *當mHardBitmapCache的key大於30的時候,會根據LRU演算法把最近沒有被使用的key放入到這個緩衝中。
- *Bitmap使用了SoftReference,當記憶體空間不足時,此cache中的bitmap會被記憶體回收掉
- */
- private final staticConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache =new ConcurrentHashMap
複製代碼
系列之Android 遠程圖片擷取和本機快取(一)的文章連結http://www.eoeandroid.com/thread-98446-1-1.html
系列之Android 遠程圖片擷取和本機快取(三)的文章連結http://www.eoeandroid.com/thread-98450-1-1.html