我正在编写一个应用程序来显示网站上的帖子并使用Html.fromHtml
来执行此操作。但是,如果我打开一篇文章,它会立即使用大约25MB的内存来加载图像。这是可以接受的,即使图像存储在设备上,只重新加载同一篇文章会导致另外25MB的跳转。我环顾四周,尝试了大量的解决方案。我觉得我只需要回收位图,我不知道该怎么做。这是代码:
public class ImageGetter implements Html.ImageGetter {
private Context c;
private TextView container;
private ImageLoader imageLoader;
private DisplayImageOptions options;
private UrlImageDownloader urlDrawable;
public ImageGetter(View t, Context c) {
this.c = c;
this.container = (TextView)t;
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(false).imageScaleType(ImageScaleType.EXACTLY)
.showImageOnLoading(R.color.darkcolorPrimary).bitmapConfig(Bitmap.Config.RGB_565).resetViewBeforeLoading(true).build();
}
@Override
public Drawable getDrawable(String source) {
urlDrawable = new UrlImageDownloader(c.getResources(), source);
imageLoader.loadImage(source, options, new SimpleListener(urlDrawable));
return urlDrawable;
}
private class SimpleListener extends SimpleImageLoadingListener
{
UrlImageDownloader urlImageDownloader;
public SimpleListener(UrlImageDownloader downloader) {
super();
urlImageDownloader = downloader;
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
int width = loadedImage.getWidth();
int height = loadedImage.getHeight();
int newWidth = width;
int newHeight = height;
if( width > container.getWidth() ) {
newWidth = container.getWidth();
newHeight = (newWidth * height) / width;
}
Drawable result = new BitmapDrawable(c.getResources(), loadedImage);
result.setBounds(0, 0, newWidth, newHeight);
urlImageDownloader.setBounds(0, 0, newWidth, newHeight);
urlImageDownloader.drawable = result;
container.setText(container.getText());
}
}
public class UrlImageDownloader extends BitmapDrawable
{
public Drawable drawable;
/**
* Create a drawable by decoding a bitmap from the given input stream.
*
* @param res
* @param is
*/
public UrlImageDownloader(Resources res, InputStream is) {
super(res, is);
}
/**
* Create a drawable by opening a given file path and decoding the bitmap.
*
* @param res
* @param filepath
*/
public UrlImageDownloader(Resources res, String filepath) {
super(res, filepath);
drawable = new BitmapDrawable(res, filepath);
}
/**
* Create drawable from a bitmap, setting initial target density based on
* the display metrics of the resources.
*
* @param res
* @param bitmap
*/
public UrlImageDownloader(Resources res, Bitmap bitmap) {
super(res, bitmap);
}
@Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if(drawable != null) {
drawable.draw(canvas);
}
}
}
}
答案 0 :(得分:1)
解决。存在内存泄漏涉及存储图像的TextView
。如果您遇到这样的问题,我建议使用Eclipse MAT来识别内存泄漏。
答案 1 :(得分:0)
您可以通过调用recycle
方法删除位图。
但是它自己不会做太多,你应该通过调用System.gc()
来调用垃圾收集器,然后将它从内存中清除。