清空堆内存以解决 Out of Memory 异常

8

我知道关于内存不足的问题已经被问到了,但我没有找到解决方案。

在位图工厂中,我遇到了内存不足异常,即使使用了

inSampleSize=1

以前我经常在try-catch块中包含OutOfMemoryException,但这是一种不好的做法。

try{
   .........
   ......
}catch (OutOfMemoryError e)
            {}

捕获了内存不足异常,但我的问题是,在捕获这个异常后,我们应该怎么做?

清除或重新分配GC的堆内存

有解决方案吗?

我使用了

System.gc();

没有效果。请帮忙!

not even Bitmap also for GridView Orientation 
i found this exception
Clamp target GC heap from 17.333MB to 16.000MB
Out of memory on a 140416-byte allocation.

只需搜索“android 内存不足”,您将找到许多带有各种可能解决方案的问题。 - Simon
@Simon 我看到了,我以前也用过那段代码,但是显示的图片会模糊,不好看。 - Bald bcs of IT
内存不足,无法在设备上创建位图。 - T_V
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html - Muhammad Babar
1个回答

11

经过3天的努力,我找到了一个解决方案,可以避免使用这个方法增加堆内存。

我把所有我的 ImageView 替换成了这样

<com.example.util.SingleShotImageView
                    android:id="@+id/grid_image"
                    android:layout_width="170dp"
                    android:layout_height="240dp"
                    android:adjustViewBounds="true"
                    android:layout_centerInParent="true"
                     />

我用这个类在onDetachedFromWindow函数中清除图像位图堆大小。

public class SingleShotImageView extends ImageView {

    public SingleShotImageView(Context context) {
        super(context);
    }

    public SingleShotImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SingleShotImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDetachedFromWindow () {
        setImageDrawable(null);
        setBackgroundDrawable(null);
        setImageBitmap(null);
        System.gc();
    }

}

现在它可以正常工作,我的堆内存保持不变。

扩大堆(碎片情况)到11.719MB,以进行8192016字节的分配


嗨,我已经按照您说的修改了我的代码,但问题是在活动中从未调用onDetachedFromWindow()方法,而在替换片段时却会调用!因此,我的应用程序仍然在活动中崩溃。 - Hesam
哦天啊,我需要它,有些晚上没睡觉为了找到解决方案,在 onDetachedFromWindow 方法中清除自定义 ImageView。 - Hossein Kurd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接