现象:
通过AndroidStudio的Profiler工具,抓取堆栈信息后,得到内存泄漏的反馈
只知道是哪个文件泄漏了,但不知道什么原因导致的泄漏。
什么是内存泄漏?
一个对象用完后被毁掉了,但是他的引用还在,导致GC无法回收此对象占用的内存,于是导致内存泄漏。
A memory leak occurs when an object’s reference is held on to after its purpose has been served. As a result, this prevents the garbage collector from cleaning up the reference.
泄漏是怎么发生的?
How do leaks happen in fragments? First, we need to start by reviewing the important nuance of fragments. They have two different lifecycles:
It’s own lifecycle (onCreate and onDestroy)
It’s view’s lifecycle (onCreateView and onDestroyView)
Having two lifecycles for a single screen can be problematic. They are created and destroyed at different times, for instance, when putting a fragment on the back-stack. Specifically, holding onto views after onDestroyView is called will leak. This happens when a fragment is on the back stack, and although its view is destroyed, the fragment itself is not. The garbage collector is unable to clear the reference to those views.
链接:https://engineering.procore.com/fix-your-android-memory-leaks-in-fragments/
文中说Fragment的泄漏是view被摧毁了