下载大量图片内存溢出的解决方案(使用SoftReference)

使用SoftReference<Drawable>解决大量图片下载内存溢出的问题。


public DrawableManager() { 
    drawableMap = new HashMap<String, SoftReference<Drawable>>(); 
} 
 
public Drawable fetchDrawable(String urlString) { 
    SoftReference<Drawable> drawableRef = drawableMap.get(urlString); 
    if (drawableRef != null) { 
        Drawable drawable = drawableRef.get(); 
        if (drawable != null) 
            return drawable; 
        
        drawableMap.remove(urlString); 
    } 
 
    if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "image url:" + urlString); 
    try { 
        InputStream is = fetch(urlString); 
        Drawable drawable = Drawable.createFromStream(is, "src"); 
        drawableRef = new SoftReference<Drawable>(drawable); 
        drawableMap.put(urlString, drawableRef); 
        if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", " 
                + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", " 
                + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth()); 
        return drawableRef.get(); 
    } catch (MalformedURLException e) { 
        if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e); 
        return null; 
    } catch (IOException e) { 
        if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e); 
        return null; 
    } 
} 
 
public void fetchDrawableOnThread(final String urlString, final ImageView imageView) { 
    SoftReference<Drawable> drawableRef = drawableMap.get(urlString); 
    if (drawableRef != null) { 
        Drawable drawable = drawableRef.get(); 
        if (drawable != null) { 
            imageView.setImageDrawable(drawableRef.get()); 
            return; 
        } 
        // Reference has expired so remove the key from drawableMap 
        drawableMap.remove(urlString); 
    } 
 
    final Handler handler = new Handler() { 
        @Override 
        public void handleMessage(Message message) { 
            imageView.setImageDrawable((Drawable) message.obj); 
        } 
    }; 
 
    Thread thread = new Thread() { 
        @Override 
        public void run() { 
            //TODO : set imageView to a "pending" image 
            Drawable drawable = fetchDrawable(urlString); 
            Message message = handler.obtainMessage(1, drawable); 
            handler.sendMessage(message); 
        } 
    }; 
    thread.start(); 
} 

转自:  http://wang-peng1.iteye.com/blog/719116

你可能感兴趣的:(thread,image,String,null,url,reference)