当前位置: 代码迷 >> Android >> [Android漫笔]内存泄漏以及内存溢出
  详细解决方案

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

热度:23   发布时间:2016-04-27 23:19:49.0
[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在一个屏幕上显示多张图片


版权声明:本文为博主原创文章,未经博主允许不得转载。

  相关解决方案