[Android随笔]内存泄漏以及内存溢出

名词解释     


      内存泄漏:memory leak,是指程序在申请内存后,无法释放已申请的内存空间,一次内存泄漏危害能够忽略,但内存泄漏堆积后果非常严重,不管多少内存,迟早会被占光。

      内存溢出:out of memory,是指程序在申请内存时,没有足够的内存空间供其使用,出现out of memory。比方申请了一个Integer,但给它存了Long才干存下的数。那就是内存溢出。除此之外,也有一次性申请非常多内存。比方说一次创建大的数组或者是加载一个大文件如图片。非常多时候是图片的处理不当。

      memory leak 会终于导致out of memory!

内存泄漏举例

1。Android数据库查询时会使用Cursor。可是在写代码时。常常会有人忘记调用close,或者由于代码逻辑问题导致close未被调用。

2。I/O数据流操作,读写结束后没有关闭。

3,Bitmap使用后未调用recycle();

4,调用registerReceiver后未调用unregisterReceiver().

5,还有种比較隐晦的Context泄漏

先让我门看一下下面代码:

    private static Drawable sBackground;
    @Override
    protected void onCreate(Bundle state) {
        super.onCreate(state);
        TextView label = new TextView(this);
        label.setText("Leaks are bad");
        if (sBackground == null) {
            sBackground = getDrawable(R.drawable.large_bitmap);
        }
        label.setBackgroundDrawable(sBackground);
        setContentView(label);
    }

代码说明:在这段代码中,我们使用一个static的Drawable对象。这通常发生在我们须要常常调用一个Drawable。而其载入又比較耗时,不希望每次载入Activity都去创建这个Drawable的情况。此时。使用static无疑是最快的代码编写方式,可是其也很的糟糕。当一个Drawable被附加到View时,这个View会被设置为这个Drawable的callback (通过调用Drawable.setCallback()实现)。这就意味着。这个Drawable拥有一个TextView的引用,而TextView又拥有一个Activity的引用。这就会导致Activity在销毁后,内存不会被释放。

解决方式:Avoiding Memory Leaks 文章提到

In summary, to avoid context-related memory leaks, remember the following:
1。Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
2。Try using the context-application instead of a context-activity
3。Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solutionto  this issue is to use a static inner class with a  to the outer class, as done in  and its W inner class for instance
4,A garbage collector is not an insurance against memory leaks

一些避免内存泄漏的点能够看看[Android随笔]内存优化纪录篇

内存溢出举例

1,一次性载入一个大文件如图片,载入大图片的解决方式[Android随笔]怎样有效载入显示图片

2,使用List View、GridView在一个屏幕上显示多张图片


原文地址:https://www.cnblogs.com/claireyuancy/p/6925456.html