Created
February 3, 2012 17:24
-
-
Save ligi/1731265 to your computer and use it in GitHub Desktop.
DiscCache implementation for com.nostra13.universalimageloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
import com.nostra13.universalimageloader.cache.disc.DiscCache; | |
/** | |
* DiscCache implementation that takes care that | |
* the cache is not growing like cancer | |
* | |
* As argument for deleting we use the lastModified TimeStamp | |
* old files get deleted | |
* for every use of the file we update the lastModified | |
* to the actual time so that files that are used are not killed | |
* | |
* @author ligi | |
* | |
*/ | |
public class ImageDiscCache extends DiscCache { | |
private final static int MAX_FILES=200; | |
private final static int CALL_EVERY=400; | |
private int call_to_getFile_count=0; | |
public ImageDiscCache(File cacheDir) { | |
super(cacheDir); | |
checkAndDeleteFilesRun(); | |
} | |
/** | |
* checks if we have to many files and if we do: | |
* remove the ones with the oldest lastMod timestamp | |
*/ | |
private void checkAndDeleteFilesRun() { | |
call_to_getFile_count=0; | |
File[] files_in_cache=getCacheDir().listFiles(); | |
if (files_in_cache==null) | |
return; | |
if (files_in_cache.length<MAX_FILES) | |
return; // not to many files nothing to do yet | |
HashMap <Long,File> lastMod2file=new HashMap<Long,File>(); | |
for (File act_file : files_in_cache) { | |
Long key=act_file.lastModified(); | |
while (lastMod2file.containsKey(key)) | |
key++; | |
lastMod2file.put(key, act_file); | |
} | |
Long[] timestamp_arr=lastMod2file.keySet().toArray(new Long[] {}); | |
Arrays.sort(timestamp_arr); | |
for (int i=0;i<(files_in_cache.length-MAX_FILES);i++) { | |
lastMod2file.get(timestamp_arr[i]).delete(); | |
} | |
} | |
@Override | |
public File getFile(String url) { | |
String fileName = String.valueOf(url.hashCode()); | |
if ((call_to_getFile_count++)>CALL_EVERY) | |
checkAndDeleteFilesRun(); | |
File res=new File(getCacheDir(), fileName); | |
res.setLastModified(System.currentTimeMillis()); // if the file gets used we want to keep it - no matter when it came in | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment