1、为什么要异步加载图片?
2、缓存的实现(SoftReference)?
栈内存:存放对象的引用。堆内存:存放对象。引用指向对象,当对象的引用不再指向某个对象,或者对象无引用指向,垃圾回收器就会把他们回收。
SoftReference :软引用,非完成的引用。当垃圾回收机制启动时,首先判断内存是否已满,如果未满,则不对软引用做处理,但是,当内存已满时,会把软引用回收。
SoftReference<Object> sr=new SoftReference<Object>(new Object());
Object obj=sr.get();
3、异步加载图片的方法?
- public class AsyncImageLoader {
- //key:图片的URL value:SoftReference对象,该对象指向一个Drawable对象
- private HashMap<String, SoftReference<Drawable>> imageCache;
- public AsyncImageLoader() {
- imageCache = new HashMap<String, SoftReference<Drawable>>();
- }
- public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
- if (imageCache.containsKey(imageUrl)) { //首先判断缓存中是否含有该图片,存在的话获取并返回
- SoftReference<Drawable> softReference = imageCache.get(imageUrl);
- Drawable drawable = softReference.get();
- if (drawable != null) {
- return drawable;
- }
- }
- final Handler handler = new Handler() { //不存在的话,在线程中加载,并通过Handler发送至UI线程
- public void handleMessage(Message message) {
- imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
- }
- };
- new Thread() {
- @Override
- public void run() {
- Drawable drawable = loadImageFromUrl(imageUrl);
- imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
- Message message = handler.obtainMessage(0, drawable);
- handler.sendMessage(message);
- }
- }.start();
- return null;
- }
- public static Drawable loadImageFromUrl(String url) { //通过图片url获取图片资源
- URL m;
- InputStream i = null;
- try {
- m = new URL(url);
- i = (InputStream) m.getContent();
- } catch (MalformedURLException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- Drawable d = Drawable.createFromStream(i, "src");
- return d;
- }
- public interface ImageCallback { //自定义一个接口,
- public void imageLoaded(Drawable imageDrawable, String imageUrl);
- }
- }