我在 TabHost
中有一个 Activity
以及其他 3 个 Activity 。因此,它们始终处于 Activity 状态(或处于“暂停”状态)。
第一个 Activity 有四个不同的图像(每个大约 250kb),它们正在检索大量内存(大约 80MB。需要指出的是,我加载了屏幕所需的最小尺寸,并且我正在使用 layout_weight
如果有帮助的话),所以我想尽量减少所需的内存量。
我已经尝试在 OnPause
状态下删除图像并在 OnResume
状态下重新设置它们,但我没有运气,这是我的一个例子正在尝试做:
imageView.Drawable.Callback = null;
((BitmapDrawable)imageView.Drawable).Bitmap.Recycle();
imageView.Drawable.Dispose();
imageView.SetImageDrawable(null);
imageView.SetImageBitmap(null);
GC.Collect();
我不知道在 OnPause
上删除 Bitmap
是否是最好的策略,但它应该有效。我不明白为什么 GC 不收集 ImageView
(因为没有外部引用)
编辑 这就是我加载图像的方式。即使我将图像放在 xml 文件中,它也不起作用。此外,我不关心这段代码,我只想处理位图。
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()
成功了。
关于android - 回收位图不释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20736558/