如何使用软引用

  1. 什么是软引用:http://en.wikipedia.org/wiki/Soft_reference
  1. 使用软引用:

我构造了简单的HashMap来存储SoftReference的对象。

      private HashMap<Integer, SoftReference<Bitmap>> mThumbnailCache = null;//新建软引用缓存。

 

//创建一个软应用

      private SoftReference<Bitmap> createSoftReference(int albumId) {

           if (null == mCacheManager)

                 return null;

           Bitmap bmpTmp = mCacheManager.getThumbnail(getAlbumPos(albumId));

           if (null == bmpTmp)

                 return null;

            SoftReference<Bitmap> sr = new SoftReference<Bitmap>(bmpTmp);

           bmpTmp = null;//需要置空

           return sr;

      }

 

//获得软引用缓存中的Bitmap

      public Bitmap getThumbnail(int albumId) {

           if (null == mCacheManager || null == mThumbnailCache)

                 return null;

           if (mThumbnailCache.containsKey(albumId)) {

                 SoftReference<Bitmap> bmpSr = mThumbnailCache.get(albumId);

                 if (null != bmpSr && null != bmpSr.get())

                      return bmpSr.get();

                 mThumbnailCache.remove(albumId);

           }

//如果GC释放了一个SoftReference,则需要重新创建SoftReference,并且将该SoftReference存到HashMap里。

           SoftReference<Bitmap> sr = createSoftReference(albumId);

           if (null == sr)

                 return null;

           mThumbnailCache.put(albumId, sr);

           return sr.get();

      }

原文地址:https://www.cnblogs.com/androidwsjisji/p/2231349.html