Android内存管理(14)*使用开源库LeakCanary检查内存泄漏
1.简介
它是一个非常简单好用的内存泄漏检测工具库。可以轻松检测Activity,Fragment的内存泄漏。如果有内存泄漏,它会产生一个通知。
2.资料
官网:
https://github.com/square/leakcanary
官网教程:
https://github.com/square/leakcanary/wiki/FAQ
中文教程:
http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/
3.基本流程
3.1 在build.gradle中添加引用库
1 dependencies { 2 debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2' 3 releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2' 4 testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2' 5 }
3.2 在manifest.xml中添加一个Application类.
1 ... 2 <application 3 android:allowBackup="false" 4 android:name="com.e.weixin.main.presenter.WeiXinApplication" 5 android:icon="@drawable/ic_launcher" 6 android:label="@string/app_name" 7 android:theme="@style/AppBaseTheme" > 8 ...
3.3 然后用RefWatcher监视它
1 public class ExampleApplication extends Application { 2 3 public static RefWatcher getRefWatcher(Context context) { 4 ExampleApplication application = (ExampleApplication) context.getApplicationContext(); 5 return application.refWatcher; 6 } 7 8 private RefWatcher refWatcher; 9 10 @Override public void onCreate() { 11 super.onCreate(); 12 refWatcher = LeakCanary.install(this); 13 } 14 }
这样当有Activity中产生内存漏泄时,就会有通知。
可以在想要检测的Fragment中添加如下代码:
1 public abstract class BaseFragment extends Fragment { 2 3 @Override public void onDestroy() { 4 super.onDestroy(); 5 RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity()); 6 refWatcher.watch(this); 7 } 8 }
4.自定义LeakCanary
官网: https://github.com/square/leakcanary/wiki/Customizing-LeakCanary
为了不与其它使用LeakCanary库的应用产生同名的接收通知程序,可以自定义 __leak_canary_display_activity_label
1 <!-- TODO: Remove or change this placeholder text --> 2 <string name="hello_blank_fragment">Hello blank fragment</string> 3 <string name="__leak_canary_display_activity_label">WeiXinLeaks</string> 4 <integer name="__leak_canary_max_stored_leaks">20</integer> 5 <integer name="leak_canary_watch_delay_millis">1500</integer>
分类:
重要
, Android 性能优化
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?