Skip to content

Instantly share code, notes, and snippets.

@extralam
Created February 13, 2015 02:42
Show Gist options
  • Save extralam/fedd67d6e9264c3b8fdc to your computer and use it in GitHub Desktop.
Save extralam/fedd67d6e9264c3b8fdc to your computer and use it in GitHub Desktop.
Simple Url return cache
package com.extralam.utils;
import android.support.v4.util.LruCache;
/**
* A Simple url return cache;
*/
public class UrlCacheHelper {
private static final int CACHE_FACTOR = 8;
private static final long FIXED_EXP_TIME = 60 * 1000 * 1;
private static LruCache<String, CacheFork> sLocalCache;
private static void createCache() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
sLocalCache = new LruCache<String, CacheFork>(maxMemory/CACHE_FACTOR);
}
private static class CacheFork{
long exptime = FIXED_EXP_TIME;
long storeTime = 0;
String mFile;
public CacheFork(String file){
storeTime = System.currentTimeMillis();
mFile = file;
}
public CacheFork(String file , long _exptime){
storeTime = System.currentTimeMillis();
mFile = file;
setExpTime(_exptime);
}
public void setExpTime(long _exptime){
exptime = _exptime;
}
}
public static void addCache(String url , String cache){
if(sLocalCache == null){
createCache();
}
sLocalCache.put(url, new CacheFork(cache));
}
public static void addCache(String url , String cache , long _exptime){
if(sLocalCache == null){
createCache();
}
sLocalCache.put(url, new CacheFork(cache, _exptime));
}
public static String getCache(String url){
if(sLocalCache != null) {
CacheFork obj = sLocalCache.get(url);
if(obj == null || (System.currentTimeMillis() - obj.storeTime) > obj.exptime){
sLocalCache.remove(url);
}else{
return obj.mFile;
}
}
return null;
}
public static void clearCache(){
if(sLocalCache != null) {
sLocalCache.evictAll();
sLocalCache = null;
}
}
public static void clearHalfCache(){
if(sLocalCache != null) {
sLocalCache.trimToSize(sLocalCache.size() / 2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment