public class MemoryCache {
private static final String TAG = "MemoryCache";
Private map<string, bitmap> Cache=collections.synchronizedmap (
New linkedhashmap<string, bitmap> (10,1.5f,true));//last argument true for LRU ordering
Private long size=0;//current Allocated size
Private long Limit=1000000;//max memory in bytes
Public MemoryCache () {
Use 25% of available heap size
Setlimit (Runtime.getruntime (). MaxMemory ()/4);
}
public void Setlimit (long new_limit) {
Limit=new_limit;
LOG.I (TAG, "MemoryCache would use the up to" +limit/1024./1024.+ "MB");
}
Public Bitmap get (String ID) {
try{
if (!cache.containskey (ID))
return null;
NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
return Cache.get (ID);
}catch (NullPointerException ex) {
Ex.printstacktrace ();
return null;
}
}
public void put (String ID, Bitmap Bitmap) {
try{
if (Cache.containskey (ID))
Size-=getsizeinbytes (Cache.get (id));
Cache.put (ID, bitmap);
Size+=getsizeinbytes (bitmap);
Checksize ();
}catch (throwable th) {
Th.printstacktrace ();
}
}
private void Checksize () {
LOG.I (TAG, "Cache size=" +size+ "length=" +cache.size ());
if (size>limit) {
Iterator<entry<string, Bitmap>> Iter=cache.entryset (). Iterator ();//least recently accessed item'll be The first one iterated
while (Iter.hasnext ()) {
Entry<string, bitmap> entry=iter.next ();
Size-=getsizeinbytes (Entry.getvalue ());
Iter.remove ();
if (size<=limit)
Break
}
LOG.I (TAG, "clean cache. New size "+cache.size ());
}
}
public void Clear () {
try{
NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
Cache.clear ();
size=0;
}catch (NullPointerException ex) {
Ex.printstacktrace ();
}
}
Long Getsizeinbytes (Bitmap Bitmap) {
if (bitmap==null)
return 0;
return Bitmap.getrowbytes () * Bitmap.getheight ();
}
}
Android Cache Pictures