Simple Picture Cache Encapsulation Class

Source: Internet
Author: User

Directly on the code:

public class Bitmapcache {

Private lrucache<string, bitmap> lc;//Strong citation

Private hashmap<string, softreference<bitmap>> smap;//Weak reference

Public Bitmapcache () {

smap=new hashmap<string, softreference<bitmap>> ();

Take one-eighth of the memory as a strong reference cache space

lc=new mylrucache ((int) (Runtime.getruntime (). MaxMemory ()/8));


//Put the picture in the cache, take the picture as a picture to get the key

public void setimage (String url,bitmap result) {

lc.put (URL, result);


//Take the picture from the cache, take the picture as the key, get the corresponding picture

public Bitmap getImage (String URL) {

Bitmap result;

result = lc.get (URL);

if (result = = null) {

//strong references do not have pictures, go to weak references to get

softreference<bitmap> so = smap.get (URL);

if (so! = null) {

result = So.get ();

return result;


} else {

return result;


return null;


//Custom Strong reference class, when a picture in a strong reference is removed, the removed picture is added to the weak reference

class Mylrucache extends Lrucache<string, bitmap>{

public mylrucache (int maxSize) {

Super (maxSize);



protected int sizeOf (String key, Bitmap value) {

//Call GetByteCount () method, API minimum above 12

return Value.getbytecount ();



protected void entryremoved (Boolean evicted, String key,

Bitmap oldValue, Bitmap newvalue) {

smap.put (Key, New softreference<bitmap> (OldValue));




The use of this class is simple, instantiate the class,

The SetImage method of this class stores the downloaded picture and obtains the picture in the cache through the class's GetImage method.

Simple Picture Cache Encapsulation Class

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: 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.