内存泄露日志
在项目中使用LeakCanary进行内存泄漏收集的时候出现了下面的一个memory leak:
1 | 06-23 11:23:08.512 10127-19987/org.xxx.xxx D/LeakCanary: In org.kingfeng.xxx:3.6.0:27. |
功能实现
在activity中有:
1 | ServiceConnection mServiceConnection = new ServiceConnection() { |
问题原因及解决思路
看了源码中 onServiceDisconnected(ComponentName name)
方法注释:1
2
3
4
5
6
7
8
9/**
* Called when a connection to the Service has been lost. This typically
* happens when the process hosting the service has crashed or been killed.
* This does <em>not</em> remove the ServiceConnection itself -- this
* binding to the service will remain active, and you will receive a call
* to {@link #onServiceConnected} when the Service is next running.
*
* @param name The concrete component name of the service whose connection has been lost.
*/
意思就是通常情况下,在托管这个service
的进程崩溃或者被杀死的情况下,这个方法才会调用。
也就是只是Activity
销毁,这个方法并不会调用。导致connection
持有 XXXActivity
的引用,不能及时被GC回收,造成内存泄漏。
搞了好大一会儿才把这个问题解决掉,做个记录。
解决办法:
在Activity
的onDestroy()
中:
1 |
|