加载大位图之SoftReference
android2.3以前都用软引用来进行图片的缓存。
现在没人用了,了解下即可。
以下是SoftReferenceUtils。
1 public class SoftReferenceUtils { 2 3 private Map<String, SoftReference<Bitmap>> imageMap = new HashMap<>(); 4 5 public Bitmap loadBitmap(final String imageUrl, final ImageCallBack imageCallBack) { 6 7 // 取出key为imageUrl的软引用 8 SoftReference<Bitmap> reference = imageMap.get(imageUrl); 9 10 // 软引用不为空则有bitmap,直接返回bitmap 11 if (reference != null) { 12 if (reference.get() != null) { 13 return reference.get(); 14 } 15 } 16 17 // 接受网络线程传来的handler 18 final Handler handler = new Handler() { 19 public void handleMessage(final android.os.Message msg) { 20 Bitmap bitmap = (Bitmap) msg.obj; 21 //加入到缓存中 22 imageMap.put(imageUrl, new SoftReference<>(bitmap)); 23 if (imageCallBack != null) { 24 imageCallBack.getBitmap(bitmap); 25 } 26 } 27 }; 28 29 // 走到这里说明没有软引用,只能子线程下载 30 new Thread() { 31 public void run() { 32 Message message = handler.obtainMessage(); 33 message.obj = downloadBitmap(imageUrl); 34 handler.sendMessage(message); 35 } 36 }.start(); 37 38 return null; 39 } 40 41 // 从网上下载图片 42 private Bitmap downloadBitmap(String imageUrl) { 43 try { 44 return BitmapFactory.decodeStream(new URL(imageUrl).openStream()); 45 46 } catch (Exception e) { 47 e.printStackTrace(); 48 return null; 49 } 50 } 51 52 public interface ImageCallBack { 53 void getBitmap(Bitmap bitmap); 54 } 55 56 }