内存泄漏和溢出

内存泄漏: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");
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

内存溢出举例
1,一次性加载一个大文件如图片,加载大图片的解决方案[Android随笔]如何有效加载显示图片
2,使用List View、GridView在一个屏幕上显示多张图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值