本文為大家分享了android圖片加載的緩存類,供大家參考,具體內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
|
import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.lang.ref.softreference; import java.net.httpurlconnection; import java.net.url; import java.util.linkedhashmap; import java.util.concurrent.concurrenthashmap; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.os.build; import android.os.handler; import android.text.textutils; /** * 圖片加載器,主要功能是從網絡中下載圖片并緩存。這里之所以另寫一個功能類似重復的原因是 之前舊的圖片加載邏輯感覺非常復雜,我這里寫個輕量級的 * * @author h3c * */ public class imageloaderengine { public static final int load_img_success = 2010 ; private final int max_capacity = build.version.sdk_int > build.version_codes.gingerbread_mr1 ? 50 : 10 ; // 一級緩存緩存圖片數 private static imageloaderengine instance; private static handler mhandler; private executorservice pool; // 后臺線程池 // 這里用linkedhashmap不用lrucache的原因是lrucache直接申請內存大小而不是圖片個數。此app已經有一個全局的lrucache了,重復申請內存大小對應用不利 private linkedhashmap<string, bitmap> mfirstlevelcache; // <momentid>一級緩存,硬鏈接bitmap,只保留最近用的圖片。 private concurrenthashmap<string, softreference<bitmap>> msecondlevelcache; // <momentid> public static imageloaderengine getinstance(handler handler) { if (instance == null ) { instance = new imageloaderengine(); } if (handler != null ) { mhandler = handler; } return instance; } private imageloaderengine() { pool = executors.newfixedthreadpool( 4 ); // 默認線程池大小為6 initcache(); } private void initcache() { mfirstlevelcache = new linkedhashmap<string, bitmap>(max_capacity / 2 , 0 .75f, true ) { private static final long serialversionuid = 1l; protected boolean removeeldestentry(entry<string, bitmap> eldest) { if (size() > max_capacity) { // 超過一級緩存大小后會挪到二級緩存中 msecondlevelcache.put(eldest.getkey(), new softreference<bitmap>(eldest.getvalue())); return true ; } return false ; }; }; msecondlevelcache = new concurrenthashmap<string, softreference<bitmap>>(); // <momentid> } /** * 移除緩存 * @param key */ public void deletecachebykey(string key) { string sdcacheingpath = iohelper.getcachedpicturepath( global.packagename, key); string sdcacheedpath = sdcacheingpath + ".png" ; file file = new file(sdcacheingpath); if (file.exists()) { file.delete(); } file = new file(sdcacheedpath); if (file.exists()) { file.delete(); } mfirstlevelcache.remove(key); msecondlevelcache.remove(key); } /** * 釋放資源 */ public void recycleimageloader() { new thread( new runnable() { @override public void run() { if (pool != null ) { pool.shutdownnow(); } if (mfirstlevelcache != null ) { for (bitmap bmp : mfirstlevelcache.values()) { if (bmp != null ) { bmp.recycle(); bmp = null ; } } mfirstlevelcache.clear(); mfirstlevelcache = null ; } if (msecondlevelcache != null ) { msecondlevelcache.clear(); } mhandler = null ; } }).start(); } /** * 后臺請求圖片 * * @param item */ public void loadimagebymoment( final nmoment moment,string phototag) { if (moment.ispicture() || moment.isvideo()) { string id = moment.id + phototag; loadimagebyurl(id+ "" , moment.getpicture(global.widthpixels/ 3 * 2 ),moment.orientation); } } /** * 后臺請求圖片 * @param key * @param url */ public void loadimagebyurl( final string key, final string url, final int orientation) { pool.submit( new runnable() { public void run() { loghelper.e( "imageloaderengine" , "從網絡中下載" ); // 如果內存中有就算了 if (mfirstlevelcache.get(key) != null || msecondlevelcache.get(key) != null ) { // 如果圖片已經緩存了 loghelper.e( "imageloaderengine" , "下載圖片錯誤 1" ); return ; } // 如果sd卡緩存中有就算了 final string sdcacheingpath = iohelper.getcachedpicturepath( global.packagename, key); file cacheingfile = new file(sdcacheingpath); if (cacheingfile.exists()) { // 如果正在緩存就算了 long currenttime = system.currenttimemillis(); if ((currenttime - cacheingfile.lastmodified()) > 2 * 60 * 1000 ) { loghelper.e( "imageloaderengine" , "2分鐘都還沒下載完,準備刪除它.." +currenttime+ "=" +cacheingfile.lastmodified()); cacheingfile.delete(); } else { getbitmapfromnetworkandaddtomemory(url, key, orientation); loghelper.e( "imageloaderengine" , "第二次進來應該走這里.." ); return ; } } string sdcacheedpath = sdcacheingpath + ".png" ; // 緩存完成后會改名字,否則會導致緩存錯誤,圖片變黑 file cacheedfile = new file(sdcacheedpath); if (cacheedfile.exists()) { // 如果緩存了就算了 loghelper.e( "imageloaderengine" , "下載圖片錯誤 2" ); return ; } getbitmapfromnetworkandaddtomemory(url, key, orientation); } }); } private void getbitmapfromnetworkandaddtomemory(string url,string key, int orientation) { bitmap bmp = getbitmapfromurl(url); if (bmp!= null ) { loghelper.e( "imageloaderengine" , "下載網絡圖片成功" ); if (key.endswith( "_detaildaily" )) { bmp = scaledbitmap(bmp, global.getthumbwidth()); } if (orientation != 0 ) { mfirstlevelcache.put(key, viewhelper.rotatebitmap(orientation, bmp)); // 從網絡下載后直接顯示 } else { mfirstlevelcache.put(key, bmp); // 從網絡下載后直接顯示 } if (mhandler != null ) { mhandler.removemessages(load_img_success); mhandler.sendemptymessagedelayed( load_img_success, 600 ); // 延時提示沒有數據了 } final string sdcacheingpath = iohelper.getcachedpicturepath( global.packagename, key); savebitmaptofile(sdcacheingpath, bmp); } else { loghelper.e( "imageloaderengine" , "下載網絡圖片失敗..." ); } } /** * 直接從網絡中獲取 * @param url * @return */ public bitmap getbitmapfromurl(string url) { url myfileurl = null ; bitmap bitmap = null ; inputstream is = null ; try { if (!uiutils.isnetworkavailable(myapplication.getinstance())) { return null ; } myfileurl = new url(url); httpurlconnection conn = (httpurlconnection) myfileurl .openconnection(); conn.setdoinput( true ); conn.connect(); is = conn.getinputstream(); bitmap = bitmapfactory.decodestream(is); } catch (exception e) { try { if (is != null ) { is.close(); } } catch (ioexception e1) { e1.printstacktrace(); } e.printstacktrace(); } return bitmap; } public bitmap getimageinmemory(nmoment moment) { return getimageinmemory(moment, "" ); } /** * 新增接口,可以根據tag重新標識moment,這樣可以擴展應用場景,比如首頁需要大圖,進入相集頁需要小圖 * @param moment * @param phototag * @return */ public bitmap getimageinmemory(nmoment moment, string phototag) { string id = moment.id + phototag; bitmap bmp = null ; // 1. 從一級緩存中獲取 bmp = getfromfirstlevelcache(id); if (bmp != null && !bmp.isrecycled()) { loghelper.e( "imageloaderengine" , "一級緩存獲取:" +id); return bmp; } // 2. 從二級緩存中獲取 bmp = getfromsecondlevelcache(id); if (bmp != null && !bmp.isrecycled()) { loghelper.e( "imageloaderengine" , "二級緩存獲取:" +id); return bmp; } if (bmp != null && bmp.isrecycled()) { return null ; } else { return bmp; } } public void setimage(string key,bitmap picture) { mfirstlevelcache.put(key, picture); } /** * 獲取圖片 */ public bitmap getimage(nmoment moment) { return getimage(moment, "" ); } public bitmap getimage(nmoment moment, string phototag) { string id = moment.id + phototag; bitmap bmp = null ; // 1. 從一級緩存中獲取 bmp = getfromfirstlevelcache(id); if (bmp != null && !bmp.isrecycled()) { loghelper.e( "imageloaderengine" , "一級緩存獲取:" +id); return bmp; } // 2. 從二級緩存中獲取 bmp = getfromsecondlevelcache(id); if (bmp != null && !bmp.isrecycled()) { loghelper.e( "imageloaderengine" , "二級緩存獲取:" +id); return bmp; } // 3. 從sd卡緩存中獲取 bmp = getfromsdcache(moment, phototag); if (bmp != null && !bmp.isrecycled()) { loghelper.e( "imageloaderengine" , "sd卡緩存獲取:" +id); return bmp; } // 4. 從網絡中獲取 loadimagebymoment(moment, phototag); // loghelper.e("imageloaderengine","本地獲取圖片失敗:"+moment.id+"="+moment.getpicture()); if (bmp != null && bmp.isrecycled()) { return null ; } else { return bmp; } } public bitmap getimage(string key,string url) { bitmap bmp = null ; // 1. 從一級緩存中獲取 bmp = getfromfirstlevelcache(key); if (bmp != null && !bmp.isrecycled()) { return bmp; } // 2. 從二級緩存中獲取 bmp = getfromsecondlevelcache(key); if (bmp != null && !bmp.isrecycled()) { return bmp; } // 3. 從sd卡緩存中獲取 bmp = getfromsdcachebykey(key, 0 ); if (bmp != null && !bmp.isrecycled()) { return bmp; } // 4. 從網絡中獲取 loadimagebyurl(key, url, 0 ); if (bmp != null && bmp.isrecycled()) { return null ; } else { return bmp; } } /** * 一級緩存獲取圖片 * * @param imgid * @return */ private bitmap getfromfirstlevelcache(string imgid) { bitmap bitmap = null ; synchronized (mfirstlevelcache) { bitmap = mfirstlevelcache.get(imgid); if (bitmap != null ) { mfirstlevelcache.remove(imgid); mfirstlevelcache.put(imgid, bitmap); } } return bitmap; } /** * 二級緩存獲取圖片 * * @param url * @return */ private bitmap getfromsecondlevelcache(string imgid) { bitmap bitmap = null ; softreference<bitmap> softreference = msecondlevelcache.get(imgid); if (softreference != null ) { bitmap = softreference.get(); if (bitmap == null ) { msecondlevelcache.remove(imgid); } } return bitmap; } /** * 從sd卡緩存獲取圖片,并放入一級緩存中 * * @param moment * @return * @throws ioexception */ private bitmap getfromsdcache( final nmoment moment, final string phototag) { bitmap drawable = null ; string id = moment.id + phototag; string sdcacheingpath = iohelper.getcachedpicturepath(global.packagename, id); string sdcacheedpath = sdcacheingpath + ".png" ; if (moment.islocal){ if (moment.isvideo()) { //獲取本地路徑 sdcacheedpath = moment.getpicture(global.widthpixels/ 3 * 2 ); } else { sdcacheedpath = moment.local_res_path; } } file cachefile = new file(sdcacheedpath); if (!cachefile.exists()) { // 如果沒有緩存完成就退出 loghelper.e( "imageloaderengine" , "找不到緩存文件:" +sdcacheedpath); if (!textutils.isempty(moment.local_res_path)) { // 如果本地有圖片,就先用本地圖片代替 sdcacheedpath = moment.local_res_path; cachefile = new file(sdcacheedpath); if (cachefile.exists() && !globaldata.phone_manufacturer.equalsignorecase( "samsung" )) { loghelper.e( "imageloaderengine" , "ak47...:" +globaldata.phone_manufacturer); // 先從本地找替代圖片.. new thread( new runnable() { // 從網絡下載 @override public void run() { loadimagebymoment(moment, phototag); } }).start(); return getfitphoto(sdcacheedpath, moment, cachefile); } else { return null ; } } else { return null ; } } drawable = getfitphoto(sdcacheedpath, moment, cachefile); if (drawable != null ) { if (moment.orientation != 0 ) { drawable = viewhelper .rotatebitmap(moment.orientation, drawable); } if (mfirstlevelcache != null ) { mfirstlevelcache.put(id, drawable); } } else { cachefile.delete(); } return drawable; } private bitmap getfitphoto(string sdcacheedpath,nmoment moment,file cachefile) { fileinputstream fs = null ; bitmap result; try { bitmapfactory.options options = new bitmapfactory.options(); options.injustdecodebounds = true ; bitmapfactory.decodefile(sdcacheedpath, options); int hratio = ( int ) math.ceil(options.outheight / ( float ) moment.picture_height); // 算高度 int wratio = ( int ) math.ceil(options.outwidth / ( float ) global.widthpixels); // 算寬度 if (hratio > 1 || wratio > 1 ) { if (hratio > wratio) { options.insamplesize = hratio; } else options.insamplesize = wratio; } options.inpurgeable = true ; options.ininputshareable = true ; options.indither = false ; options.injustdecodebounds = false ; try { fs = new fileinputstream(cachefile); } catch (filenotfoundexception e) { e.printstacktrace(); } result = bitmapfactory.decodefiledescriptor(fs.getfd(), null , options); } catch (exception e) { throw new runtimeexception(e); } finally { if (fs != null ) { try { fs.close(); } catch (ioexception e) { e.printstacktrace(); } } } return result; } private bitmap getfromsdcachebykey(string key, int orientation) { bitmap drawable = null ; fileinputstream fs = null ; string sdcacheedpath = iohelper.getcachedpicturepath( global.packagename, key) + ".png" ; file cachefile = new file(sdcacheedpath); if (!cachefile.exists()) { // 如果沒有緩存完成就退出 return null ; } try { bitmapfactory.options options = new bitmapfactory.options(); options.injustdecodebounds = true ; bitmapfactory.decodefile(sdcacheedpath, options); int wratio = ( int ) math.ceil(options.outwidth / ( float ) global.widthpixels); // 算寬度 options.insamplesize = wratio; options.inpurgeable = true ; options.ininputshareable = true ; options.indither = false ; options.injustdecodebounds = false ; try { fs = new fileinputstream(cachefile); } catch (filenotfoundexception e) { e.printstacktrace(); } drawable = bitmapfactory.decodefiledescriptor(fs.getfd(), null , options); if (drawable != null ) { if (orientation != 0 ) { drawable = viewhelper.rotatebitmap(orientation, drawable); } mfirstlevelcache.put(key, drawable); } else { cachefile.delete(); } } catch (exception e) { throw new runtimeexception(e); } finally { if (fs != null ) { try { fs.close(); } catch (ioexception e) { e.printstacktrace(); } } } return drawable; } /** * 創建一個灰色的默認圖 * @param moment * @return */ public bitmap getdefaultbitmap(nmoment moment) { return imagehelper.createbitmap(moment.picture_width, moment.picture_height, r.color.image_bg_daily); } /** * 保存bitmap文件到sd卡,傳入jpg結尾的路徑 * @param filepath * @param mbitmap */ public void savebitmaptofile(string filepath, bitmap mbitmap) { try { file file = new file(filepath); if (!file.getparentfile().exists()) { file.getparentfile().mkdirs(); } if (file.exists() && file.length() > 0 ) { long currenttime = system.currenttimemillis(); if ((currenttime - file.lastmodified()) > 2 * 60 * 1000 ) { loghelper.e( "imageloaderengine" , "2分鐘都還沒下載完,準備刪除它.." + currenttime + "=" + file.lastmodified()); file.delete(); } else { return ; } } else { file.createnewfile(); } fileoutputstream fout = null ; fout = new fileoutputstream(file); mbitmap.compress(bitmap.compressformat.jpeg, 80 , fout); fout.flush(); fout.close(); file.renameto( new file(filepath+ ".png" )); } catch (exception e) { e.printstacktrace(); loghelper.e( "imageloaderengine" , "保存圖片錯誤:" +e); } loghelper.e( "imageloaderengine" , "保存網絡圖片成功" +filepath+ ".png" ); } /** * 保存文件至緩存,這里重寫而不用iohelper里面的原因是iohelper里面過于復雜 * * @param url * @param filepath * @return */ public boolean saveurlbitmaptofile(string url, string filepath) { if (textutils.isempty(filepath)) { return false ; } file iconfile = new file(filepath); if (iconfile.getparentfile() == null ) { return false ; } if (!iconfile.getparentfile().exists()) { iconfile.getparentfile().mkdirs(); } if (iconfile.exists() && iconfile.length() > 0 ) { long currenttime = system.currenttimemillis(); if ((currenttime - iconfile.lastmodified()) > 2 * 60 * 1000 ) { loghelper.e( "imageloaderengine" , "2分鐘都還沒下載完,準備刪除它.." +currenttime+ "=" +iconfile.lastmodified()); iconfile.delete(); } else { return true ; } } fileoutputstream fos = null ; inputstream is = null ; try { fos = new fileoutputstream(filepath); is = new url(url).openstream(); int data = is.read(); while (data != - 1 ) { fos.write(data); data = is.read(); } } catch (ioexception e) { loghelper.e( "imageloaderengine" , "imageloaderengine 下載圖片錯誤" + e); iconfile.delete(); e.printstacktrace(); return false ; } finally { try { if (is != null ) { is.close(); } if (fos != null ) { fos.close(); } } catch (ioexception e) { e.printstacktrace(); } } iconfile.renameto( new file(filepath+ ".png" )); return true ; } /** * 縮放bitmap * @param bmp * @param scaledvalue縮放值 * @return */ public bitmap scaledbitmap(bitmap bmp, int scaledvalue) { int bmpwidth = bmp.getwidth(); int bmpheight = bmp.getheight(); if (bmpwidth >= bmpheight) { // 橫圖 bmpwidth = (bmpwidth * scaledvalue / bmpheight); bmpheight = scaledvalue; } else { bmpheight = (bmpheight * scaledvalue / bmpwidth); bmpwidth = scaledvalue; } bitmap scaledbmp = bitmap.createscaledbitmap(bmp,bmpwidth,bmpheight, true ); bmp.recycle(); bmp = null ; return scaledbmp; } } |
以上就是一個完整的android圖片加載緩存類,希望對大家的學習有所幫助。