前言

记得很久之前我写了一篇banner的文章,好多朋友找我要代码,并要我开放banner中使用的图片管理工厂-ImageManager。如果想很好地理解下面的故事,请参看我半年前写的两篇博文:android中图片的三级cache策略(内存、文件、网络) 一和android中左右滑屏的实现(广告位banner组件)。当时没有发上来是由于如下几点原因:首先代码较多,其次当时写的时候也参考了网络上存在的三级cache策略(大同小异),并且采用了Android项目中开源的LruCache页面淘汰算法(近期最少使用算法),还有一点就是这是实际项目使用的代码,不便直接开放,但是现在我决定把它稍作修改后开放给大家。这里我想说说那个banner,平心而论,banner的代码很多,如果采用ViewPager之类的则可以减少不少代码,但是我更看重banner的实现思想以及它的封装和事件传递,在自定义控件的封装和架构上,我到现在还觉得banner是及其成功的,尤其是banner和ImageManager结合以后,整个功能浑然天成,超高内聚,使用起来及其方便,最少只需要两行代码,你不需要导入xml,也不需要处理Json拉取策略,因为相关业务层都被封装在了banner内部,对外只保留很少的几个接口,只要实现它就能和banner内部进行交互。下面我将要介绍三级cache策略之二:内存缓存策略。

内存缓存策略

当有一个图片要去从网络下载的时候,我们并不会直接去从网络下载,因为在这个时代,用户的流量是宝贵的,耗流量的应用是不会得到用户的青睐的。那我们该怎么办呢?这样,我们会先从内存缓存中去查找是否有该图片,如果没有就去文件缓存中查找是否有该图片,如果还没有,我们就从网络下载图片。本博文的侧重点是如何做内存缓存,内存缓存的查找策略是:先从强引用缓存中查找,如果没有再从软引用缓存中查找,如果在软引用缓存中找到了,就把它移入强引用缓存;如果强引用缓存满了,就会根据Lru算法把某些图片移入软引用缓存,如果软引用缓存也满了,最早的软引用就会被删除。这里,我有必要说明下几个概念:强引用、软引用、弱引用、Lru。

强引用:就是直接引用一个对象,一般的对象引用均是强引用

软引用:引用一个对象,当内存不足并且除了我们的引用之外没有其他地方引用此对象的情况 下,该对象会被gc回收

弱引用:引用一个对象,当除了我们的引用之外没有其他地方引用此对象的情况下,只要gc被调用,它就会被回收(请注意它和软引用的区别)

Lru:Least Recently Used 近期最少使用算法,是一种页面置换算法,其思想是在缓存的页面数目固定的情况下,那些最近使用次数最少的页面将被移出,对于我们的内存缓存来说,强引用缓存大小固定为4M,如果当缓存的图片大于4M的时候,有些图片就会被从强引用缓存中删除,哪些图片会被删除呢,就是那些近期使用次数最少的图片。

代码

[java] view plain copy
  1. publicclassImageMemoryCache{
  2. /**
  3. *从内存读取数据速度是最快的,为了更大限度使用内存,这里使用了两层缓存。
  4. *强引用缓存不会轻易被回收,用来保存常用数据,不常用的转入软引用缓存。
  5. */
  6. privatestaticfinalStringTAG="ImageMemoryCache";
  7. privatestaticLruCache<String,Bitmap>mLruCache;//强引用缓存
  8. privatestaticLinkedHashMap<String,SoftReference<Bitmap>>mSoftCache;//软引用缓存
  9. privatestaticfinalintLRU_CACHE_SIZE=4*1024*1024;//强引用缓存容量:4MB
  10. privatestaticfinalintSOFT_CACHE_NUM=20;//软引用缓存个数
  11. //在这里分别初始化强引用缓存和弱引用缓存
  12. publicImageMemoryCache(){
  13. mLruCache=newLruCache<String,Bitmap>(LRU_CACHE_SIZE){
  14. @Override
  15. //sizeOf返回为单个hashmapvalue的大小
  16. protectedintsizeOf(Stringkey,Bitmapvalue){
  17. if(value!=null)
  18. returnvalue.getRowBytes()*value.getHeight();
  19. else
  20. return0;
  21. }
  22. @Override
  23. protectedvoidentryRemoved(booleanevicted,Stringkey,
  24. BitmapoldValue,BitmapnewValue){
  25. if(oldValue!=null){
  26. //强引用缓存容量满的时候,会根据LRU算法把最近没有被使用的图片转入此软引用缓存
  27. Logger.d(TAG,"LruCacheisfull,movetoSoftRefernceCache");
  28. mSoftCache.put(key,newSoftReference<Bitmap>(oldValue));
  29. }
  30. }
  31. };
  32. mSoftCache=newLinkedHashMap<String,SoftReference<Bitmap>>(
  33. SOFT_CACHE_NUM,0.75f,true){
  34. privatestaticfinallongserialVersionUID=1L;
  35. /**
  36. *当软引用数量大于20的时候,最旧的软引用将会被从链式哈希表中移出
  37. */
  38. @Override
  39. protectedbooleanremoveEldestEntry(
  40. Entry<String,SoftReference<Bitmap>>eldest){
  41. if(size()>SOFT_CACHE_NUM){
  42. Logger.d(TAG,"shouldremovetheeldestfromSoftReference");
  43. returntrue;
  44. }
  45. returnfalse;
  46. }
  47. };
  48. }
  49. /**
  50. *从缓存中获取图片
  51. */
  52. publicBitmapgetBitmapFromMemory(Stringurl){
  53. Bitmapbitmap;
  54. //先从强引用缓存中获取
  55. synchronized(mLruCache){
  56. bitmap=mLruCache.get(url);
  57. if(bitmap!=null){
  58. //如果找到的话,把元素移到LinkedHashMap的最前面,从而保证在LRU算法中是最后被删除
  59. mLruCache.remove(url);
  60. mLruCache.put(url,bitmap);
  61. Logger.d(TAG,"getbmpfromLruCache,url="+url);
  62. returnbitmap;
  63. }
  64. }
  65. //如果强引用缓存中找不到,到软引用缓存中找,找到后就把它从软引用中移到强引用缓存中
  66. synchronized(mSoftCache){
  67. SoftReference<Bitmap>bitmapReference=mSoftCache.get(url);
  68. if(bitmapReference!=null){
  69. bitmap=bitmapReference.get();
  70. if(bitmap!=null){
  71. //将图片移回LruCache
  72. mLruCache.put(url,bitmap);
  73. mSoftCache.remove(url);
  74. Logger.d(TAG,"getbmpfromSoftReferenceCache,url="+url);
  75. returnbitmap;
  76. }else{
  77. mSoftCache.remove(url);
  78. }
  79. }
  80. }
  81. returnnull;
  82. }
  83. /**
  84. *添加图片到缓存
  85. */
  86. publicvoidaddBitmapToMemory(Stringurl,Bitmapbitmap){
  87. if(bitmap!=null){
  88. synchronized(mLruCache){
  89. mLruCache.put(url,bitmap);
  90. }
  91. }
  92. }
  93. publicvoidclearCache(){
  94. mSoftCache.clear();
  95. }
  96. }

另外,给出LruCache供大家参考:

[java] view plain copy
  1. /*
  2. *Copyright(C)2011TheAndroidOpenSourceProject
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. /**
  17. *Cache保存一个强引用来限制内容数量,每当Item被访问的时候,此Item就会移动到队列的头部。
  18. *当cache已满的时候加入新的item时,在队列尾部的item会被回收。
  19. *
  20. *如果你cache的某个值需要明确释放,重写entryRemoved()
  21. *
  22. *如果key相对应的item丢掉啦,重写create().这简化了调用代码,即使丢失了也总会返回。
  23. *
  24. *默认cache大小是测量的item的数量,重写sizeof计算不同item的大小。
  25. *
  26. *<pre>{@code
  27. *intcacheSize=4*1024*1024;//4MiB
  28. *LruCache<String,Bitmap>bitmapCache=newLruCache<String,Bitmap>(cacheSize){
  29. *protectedintsizeOf(Stringkey,Bitmapvalue){
  30. *returnvalue.getByteCount();
  31. *}
  32. *}}</pre>
  33. *
  34. *<p>Thisclassisthread-safe.Performmultiplecacheoperationsatomicallyby
  35. *synchronizingonthecache:<pre>{@code
  36. *synchronized(cache){
  37. *if(cache.get(key)==null){
  38. *cache.put(key,value);
  39. *}
  40. *}}</pre>
  41. *
  42. *不允许key或者value为null
  43. *当get(),put(),remove()返回值为null时,key相应的项不在cache中
  44. */
  45. publicclassLruCache<K,V>{
  46. privatefinalLinkedHashMap<K,V>map;
  47. /**Sizeofthiscacheinunits.Notnecessarilythenumberofelements.*/
  48. privateintsize;//已经存储的大小
  49. privateintmaxSize;//规定的最大存储空间
  50. privateintputCount;//put的次数
  51. privateintcreateCount;//create的次数
  52. privateintevictionCount;//回收的次数
  53. privateinthitCount;//命中的次数
  54. privateintmissCount;//丢失的次数
  55. /**
  56. *@parammaxSizeforcachesthatdonotoverride{@link#sizeOf},thisis
  57. *themaximumnumberofentriesinthecache.Forallothercaches,
  58. *thisisthemaximumsumofthesizesoftheentriesinthiscache.
  59. */
  60. publicLruCache(intmaxSize){
  61. if(maxSize<=0){
  62. thrownewIllegalArgumentException("maxSize<=0");
  63. }
  64. this.maxSize=maxSize;
  65. this.map=newLinkedHashMap<K,V>(0,0.75f,true);
  66. }
  67. /**
  68. *通过key返回相应的item,或者创建返回相应的item。相应的item会移动到队列的头部,
  69. *如果item的value没有被cache或者不能被创建,则返回null。
  70. */
  71. publicfinalVget(Kkey){
  72. if(key==null){
  73. thrownewNullPointerException("key==null");
  74. }
  75. VmapValue;
  76. synchronized(this){
  77. mapValue=map.get(key);
  78. if(mapValue!=null){
  79. hitCount++;
  80. returnmapValue;
  81. }
  82. missCount++;
  83. }
  84. /*
  85. *Attempttocreateavalue.Thismaytakealongtime,andthemap
  86. *maybedifferentwhencreate()returns.Ifaconflictingvaluewas
  87. *addedtothemapwhilecreate()wasworking,weleavethatvaluein
  88. *themapandreleasethecreatedvalue.
  89. */
  90. VcreatedValue=create(key);
  91. if(createdValue==null){
  92. returnnull;
  93. }
  94. synchronized(this){
  95. createCount++;
  96. mapValue=map.put(key,createdValue);
  97. if(mapValue!=null){
  98. //Therewasaconflictsoundothatlastput
  99. map.put(key,mapValue);
  100. }else{
  101. size+=safeSizeOf(key,createdValue);
  102. }
  103. }
  104. if(mapValue!=null){
  105. entryRemoved(false,key,createdValue,mapValue);
  106. returnmapValue;
  107. }else{
  108. trimToSize(maxSize);
  109. returncreatedValue;
  110. }
  111. }
  112. /**
  113. *Caches{@codevalue}for{@codekey}.Thevalueismovedtotheheadof
  114. *thequeue.
  115. *
  116. *@returnthepreviousvaluemappedby{@codekey}.
  117. */
  118. publicfinalVput(Kkey,Vvalue){
  119. if(key==null||value==null){
  120. thrownewNullPointerException("key==null||value==null");
  121. }
  122. Vprevious;
  123. synchronized(this){
  124. putCount++;
  125. size+=safeSizeOf(key,value);
  126. previous=map.put(key,value);
  127. if(previous!=null){
  128. size-=safeSizeOf(key,previous);
  129. }
  130. }
  131. if(previous!=null){
  132. entryRemoved(false,key,previous,value);
  133. }
  134. trimToSize(maxSize);
  135. returnprevious;
  136. }
  137. /**
  138. *@parammaxSizethemaximumsizeofthecachebeforereturning.Maybe-1
  139. *toevicteven0-sizedelements.
  140. */
  141. privatevoidtrimToSize(intmaxSize){
  142. while(true){
  143. Kkey;
  144. Vvalue;
  145. synchronized(this){
  146. if(size<0||(map.isEmpty()&&size!=0)){
  147. thrownewIllegalStateException(getClass().getName()
  148. +".sizeOf()isreportinginconsistentresults!");
  149. }
  150. if(size<=maxSize){
  151. break;
  152. }
  153. /*
  154. *Map.Entry<K,V>toEvict=map.eldest();
  155. */
  156. //modifybyechy
  157. Iterator<Entry<K,V>>iter=map.entrySet().iterator();
  158. Map.Entry<K,V>toEvict=null;
  159. while(iter.hasNext())
  160. {
  161. toEvict=(Entry<K,V>)iter.next();
  162. break;
  163. }
  164. if(toEvict==null){
  165. break;
  166. }
  167. key=toEvict.getKey();
  168. value=toEvict.getValue();
  169. map.remove(key);
  170. size-=safeSizeOf(key,value);
  171. evictionCount++;
  172. }
  173. entryRemoved(true,key,value,null);
  174. }
  175. }
  176. /**
  177. *Removestheentryfor{@codekey}ifitexists.
  178. *
  179. *@returnthepreviousvaluemappedby{@codekey}.
  180. */
  181. publicfinalVremove(Kkey){
  182. if(key==null){
  183. thrownewNullPointerException("key==null");
  184. }
  185. Vprevious;
  186. synchronized(this){
  187. previous=map.remove(key);
  188. if(previous!=null){
  189. size-=safeSizeOf(key,previous);
  190. }
  191. }
  192. if(previous!=null){
  193. entryRemoved(false,key,previous,null);
  194. }
  195. returnprevious;
  196. }
  197. /**
  198. *Calledforentriesthathavebeenevictedorremoved.Thismethodis
  199. *invokedwhenavalueisevictedtomakespace,removedbyacallto
  200. *{@link#remove},orreplacedbyacallto{@link#put}.Thedefault
  201. *implementationdoesnothing.
  202. *
  203. *<p>Themethodiscalledwithoutsynchronization:otherthreadsmay
  204. *accessthecachewhilethismethodisexecuting.
  205. *
  206. *@paramevictedtrueiftheentryisbeingremovedtomakespace,false
  207. *iftheremovalwascausedbya{@link#put}or{@link#remove}.
  208. *@paramnewValuethenewvaluefor{@codekey},ifitexists.Ifnon-null,
  209. *thisremovalwascausedbya{@link#put}.Otherwiseitwascausedby
  210. *anevictionora{@link#remove}.
  211. */
  212. protectedvoidentryRemoved(booleanevicted,Kkey,VoldValue,VnewValue){}
  213. /**
  214. *Calledafteracachemisstocomputeavalueforthecorrespondingkey.
  215. *Returnsthecomputedvalueornullifnovaluecanbecomputed.The
  216. *defaultimplementationreturnsnull.
  217. *
  218. *<p>Themethodiscalledwithoutsynchronization:otherthreadsmay
  219. *accessthecachewhilethismethodisexecuting.
  220. *
  221. *<p>Ifavaluefor{@codekey}existsinthecachewhenthismethod
  222. *returns,thecreatedvaluewillbereleasedwith{@link#entryRemoved}
  223. *anddiscarded.Thiscanoccurwhenmultiplethreadsrequestthesamekey
  224. *atthesametime(causingmultiplevaluestobecreated),orwhenone
  225. *threadcalls{@link#put}whileanotheriscreatingavalueforthesame
  226. *key.
  227. */
  228. protectedVcreate(Kkey){
  229. returnnull;
  230. }
  231. privateintsafeSizeOf(Kkey,Vvalue){
  232. intresult=sizeOf(key,value);
  233. if(result<0){
  234. thrownewIllegalStateException("Negativesize:"+key+"="+value);
  235. }
  236. returnresult;
  237. }
  238. /**
  239. *Returnsthesizeoftheentryfor{@codekey}and{@codevalue}in
  240. *user-definedunits.Thedefaultimplementationreturns1sothatsize
  241. *isthenumberofentriesandmaxsizeisthemaximumnumberofentries.
  242. *
  243. *<p>Anentry'ssizemustnotchangewhileitisinthecache.
  244. */
  245. protectedintsizeOf(Kkey,Vvalue){
  246. return1;
  247. }
  248. /**
  249. *Clearthecache,calling{@link#entryRemoved}oneachremovedentry.
  250. */
  251. publicfinalvoidevictAll(){
  252. trimToSize(-1);//-1willevict0-sizedelements
  253. }
  254. /**
  255. *Forcachesthatdonotoverride{@link#sizeOf},thisreturnsthenumber
  256. *ofentriesinthecache.Forallothercaches,thisreturnsthesumof
  257. *thesizesoftheentriesinthiscache.
  258. */
  259. publicsynchronizedfinalintsize(){
  260. returnsize;
  261. }
  262. /**
  263. *Forcachesthatdonotoverride{@link#sizeOf},thisreturnsthemaximum
  264. *numberofentriesinthecache.Forallothercaches,thisreturnsthe
  265. *maximumsumofthesizesoftheentriesinthiscache.
  266. */
  267. publicsynchronizedfinalintmaxSize(){
  268. returnmaxSize;
  269. }
  270. /**
  271. *Returnsthenumberoftimes{@link#get}returnedavaluethatwas
  272. *alreadypresentinthecache.
  273. */
  274. publicsynchronizedfinalinthitCount(){
  275. returnhitCount;
  276. }
  277. /**
  278. *Returnsthenumberoftimes{@link#get}returnednullorrequiredanew
  279. *valuetobecreated.
  280. */
  281. publicsynchronizedfinalintmissCount(){
  282. returnmissCount;
  283. }
  284. /**
  285. *Returnsthenumberoftimes{@link#create(Object)}returnedavalue.
  286. */
  287. publicsynchronizedfinalintcreateCount(){
  288. returncreateCount;
  289. }
  290. /**
  291. *Returnsthenumberoftimes{@link#put}wascalled.
  292. */
  293. publicsynchronizedfinalintputCount(){
  294. returnputCount;
  295. }
  296. /**
  297. *Returnsthenumberofvaluesthathavebeenevicted.
  298. */
  299. publicsynchronizedfinalintevictionCount(){
  300. returnevictionCount;
  301. }
  302. /**
  303. *Returnsacopyofthecurrentcontentsofthecache,orderedfromleast
  304. *recentlyaccessedtomostrecentlyaccessed.
  305. */
  306. publicsynchronizedfinalMap<K,V>snapshot(){
  307. returnnewLinkedHashMap<K,V>(map);
  308. }
  309. @OverridepublicsynchronizedfinalStringtoString(){
  310. intaccesses=hitCount+missCount;
  311. inthitPercent=accesses!=0?(100*hitCount/accesses):0;
  312. returnString.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
  313. maxSize,hitCount,missCount,hitPercent);
  314. }
  315. }

更多相关文章

  1. android 一张图片实现 ImageView 实现 点击效果 图片明度变化
  2. Android清除数据、清除缓存、一键清理的区别
  3. 浅谈Android中的基础动画(图文详解)
  4. Android缓存机制Lrucache内存缓存和DiskLruCache磁盘缓存
  5. ReactNative之Image在Android设置圆角图片变形问题
  6. Android(安卓)OpenGLES2.0(八)——纹理贴图之显示图片
  7. Android(安卓)各种图片转黑白图和抖动算法的黑白图
  8. Android(安卓)各种菜单,弹出菜单,打开文件子菜单,文本框的复制粘贴
  9. Android(安卓)compress图片压缩介绍

随机推荐

  1. 【Android(安卓)Dev Guide - 03】 - Cont
  2. android 中管理短信
  3. Android(安卓)Debug Bridge 技术实现原理
  4. Android泡泡聊天界面的实现
  5. android UI进阶之布局的优化
  6. Android触摸事件的分发处理
  7. 开始学习android
  8. Android(安卓)WebView 访问https显示空白
  9. Ubuntu下mysql与mysql workbench安装教程
  10. mysql 5.7.18 安装配置方法图文教程(Cent