Android内存泄露问题汇总


描述
内存泄露简单说就是已经没有用的资源,但是由于被其他资源引用着
无法被GC销毁。

危害
内存泄露是内存溢出OOM的重要原因之一,会导致Crash
如果应用程序在消耗光了所有的可用堆空间(16M到48M),那么再试图在堆上分配新对象时就会引起OOM(Out Of Memory Error)异常,此时应用程序就会崩溃退出。
现在的手机内存越来越大,小的内存泄漏并不会有太大危害,但是我们是有梦想的程序员,我们想要做出精致的APP。

常见问题
1.非静态内部类,匿名内部类
2.Thread,Handler
4.ContentObserver,File,Cursor,Stream,Bitmap等资源未关闭
5.Webview
6.BraodcastReceiver,EventBus等观察者注册未注销

这个整理的比较全面


自己遇到的内存泄露问题
一.单例或一些静态资源导致内存泄漏(影响较小)
1.InputMethodManager

主要是Android OS遗留的问题
google官方确认问题
因为InputMethodManager是单例,即使泄露也不会有有很大影响,建议忽略
当然也有解决方案
leaks上给的链接
亲测6.0没生效


2.单例Dialog(或则单例View)
一直保有Context引用,销毁不了
解决方法就是不用单例了,让各个Activity new就可以了


二.注册监听广播等没有注销(影响较大)
1.RXBUS EventBus等注册监听之后没有注销,导致内存泄漏
一直保有Context引用,销毁不了

解决方案就是页面销毁是注销监听



三.WebView内存泄露(影响较大)

解决方案是用新的进程起含有WebView的Activity
<activity android:name=".activity.FundingManageActivity"
            android:process=":funding.webview"
            android:screenOrientation="portrait" />
并且在该Activity 的onDestory() 最后加上 System.exit(0); 杀死当前进程。
微信也是这么做的
weiView问题总结

四.匿名内部类(影响较小)

我们这个问题是没有应用到contex但是却引用到了
暂时没有好的解决方案,主要是内部类需要提供一些注销等方法

怎样避免内存泄露
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
And remember that a garbage collector is not an insurance against memory leaks. Last but not least, we try to make such leaks harder to make happen whenever we can.


欢迎大家关注我的简书 我的文章会在这第一时间更新


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值