回收位图不会释放内存 [英] Recycling Bitmap does not free memory
问题描述
我在TabHost
中有一个Activity
,还有其他3个活动.因此,它们始终处于活动状态(或处于暂停"状态).
I have an Activity
in a TabHost
with 3 other activities. Hence, these are always alive (or in "on pause" state).
第一个活动有四个不同的图像(每个图像约250kb),它们正在检索大量内存(约80MB.请指出,我加载了屏幕所需的最小尺寸,并且使用layout_weight
会有所帮助),所以我想最小化所需的内存量.
The first activity has four different images (~250kb each) and they are retrieving a lot of memory (around 80MB. Just to point out, I load the minimum size needed for the screen and I'm using layout_weight
if that helps), so I want to minimize the amount of memory which is needed.
我已经尝试删除处于OnPause
状态的图像,然后再次将它们设置为OnResume
,但是我没有运气,这是我正在尝试做的一个例子:
I already tried to delete the images on the OnPause
state and set them again on OnResume
, but I didn't have luck, this is one example of what I was trying to do:
imageView.Drawable.Callback = null;
((BitmapDrawable)imageView.Drawable).Bitmap.Recycle();
imageView.Drawable.Dispose();
imageView.SetImageDrawable(null);
imageView.SetImageBitmap(null);
GC.Collect();
我不知道删除OnPause
上的Bitmap
是否是最好的策略,但是应该可以.我不明白为什么GC不收集ImageView
的原因(因为没有外部引用)
I don't know if deleting the Bitmap
on OnPause
is the best strategy, but it should work. I don't understand why the ImageView
isn't collected by the GC (since there are not external references)
编辑 这就是我加载图像的方式.即使我将图像放在xml文件中也不起作用.此外,我不在乎此代码,我只想配置位图.
EDIT This is how I'm loading the images. It doesn't work even if I put the images on the xml file. Besides, I don't care this code, I just want to dispose the bitmaps.
void SetBackgroundImages(int imageId, int resId, float width, float height) {
var imageView = FindViewById<ImageView>(imageId);
using (var bitmap = DecodeSampledBitmapFromResource(Resources, resId, width, height))
imageView.SetImageBitmap(bitmap);
}
public static Bitmap DecodeSampledBitmapFromResource(Resources res, int resId, float reqWidth, float reqHeight) {
var options = new BitmapFactory.Options {InJustDecodeBounds = true};
using (var b = BitmapFactory.DecodeResource(res,resId,options)){}
options.InSampleSize = CalculateInSampleSize(options, reqWidth, reqHeight);
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeResource(res, resId, options);
}
推荐答案
最后,删除图像后调用java.lang.System.gc()
达到了目的.
At the end calling to java.lang.System.gc()
after deleting the images did the trick.
这篇关于回收位图不会释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!