【Android】内存泄漏

本文探讨了Android应用中内存泄漏的问题,特别是Fragment内存泄漏的原因。当Fragment的视图被销毁,但其自身仍然存在时,会导致内存泄漏。文章提到了Android Studio Profiler工具的使用,以及LeakCanary工具如何帮助定位和解决内存泄漏问题。通过在build.gradle中添加LeakCanary依赖,可以在Logcat中查看详细的泄漏信息,进而发现是由于未释放应用程序单例模块的监听器导致的内存泄漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现象:
通过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被摧毁了࿰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值