Android Cache Pictures

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.