Android内存泄露问题汇总

来源:互联网 发布:做java培训讲师怎么样 编辑:程序博客网 时间:2024/04/30 18:36
描述
内存泄露简单说就是已经没有用的资源,但是由于被其他资源引用着
无法被GC销毁。

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

检测工具
Leaks
https://github.com/square/leakcanary

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

这个整理的比较全面
http://blog.chinaunix.net/uid-26930580-id-3844811.html
http://blog.nimbledroid.com/2016/05/23/memory-leaks-zh.html


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

主要是Android OS遗留的问题
google官方确认问题
https://code.google.com/p/android/issues/detail?id=171190
因为InputMethodManager是单例,即使泄露也不会有有很大影响,建议忽略
当然也有解决方案
leaks上给的链接
https://gist.github.com/pyricau/4df64341cc978a7de414
亲测6.0没生效
http://www.jianshu.com/p/aa2555628b17 亲测生效


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问题总结
http://www.cnblogs.com/olartan/p/5713013.html

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

我们这个问题是没有应用到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.

http://blog.csdn.net/u010687392/article/details/49909477

0 0