本文为大家分享了Android内存泄漏排查利器,供大家参考,具体内容如下

开源地址:https://github.com/square/leakcanary

在 build.gralde 里加上依赖, 然后sync 一下, 添加内容如下

dependencies { .... debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' }

省略号代表其他已有内容

在 Application类里面将 LeakCanary 初始化。。 比如叫MyApplication ,如果没有就创建一个,继承 android.app.Application。 别忘了在AndroidManifest.xml中加上,否则不起作用

public class MyApplication extends Application { @Override public void onCreate() {  super.onCreate();  if (LeakCanary.isInAnalyzerProcess(this)) {   // This process is dedicated to LeakCanary for heap analysis.   // You should not init your app in this process.   return;  }  LeakCanary.install(this);  // 你的其他代码从下面开始 }}

官方已经有demo了,可以跑跑看。

package com.github.pandafang.leakcanarytest;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.os.SystemClock;import android.view.View;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View button = findViewById(R.id.async_task); button.setOnClickListener(new View.OnClickListener() {  @Override public void onClick(View v) {  startAsyncTask();  } }); } void startAsyncTask() { // This async task is an anonymous class and therefore has a hidden reference to the outer // class MainActivity. If the activity gets destroyed before the task finishes (e.g. rotation), // the activity instance will leak. new AsyncTask() {  @Override protected Void doInBackground(Void... params) {  // Do some slow work in background  SystemClock.sleep(20000);  return null;  } }.execute(); }}

进入主界面按下按钮, 再按返回键退出主界面, 反复几次,LeakCanary  就能探测到内存泄漏了。注意要多操作几次,1次的话泄漏规模太小,可能不会探测到。LeakCanary  一旦探测到会弹出提示的。

回到桌面,会看到一个LeakCanary 的图标,如果有多个app 用到就会有多个LeakCanary图标。

点进去就会看到内存泄漏记录

再点进去就可以看到调用栈了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多相关文章

  1. Android-- 抽屉式公告
  2. android 5.0以上通知栏、状态栏图标变成白色
  3. linux下如何为刚安装好的Eclipse在桌面建一个启动图标???(QtCreator
  4. Android屏幕大小适配问题解决
  5. Android中的软引用、弱引用
  6. [Android开发-异常]xxxActivity has leaked window com.android.
  7. Android之ToolBar项目封装,踩坑过河
  8. Android笔试和面试精华题
  9. Android获取APP的应用程序名称、包名、图标,版本号基本信息

随机推荐

  1. 初识JavaScript的基础
  2. 浅谈Vue3的几个优势
  3. 【北亚数据恢复】企业如何避免服务器数据
  4. 不联网的情况下,使用 electron-builder 快
  5. 解决vue中less的使用问题
  6. JavaScript实现进度条效果
  7. React中10种Hook的使用介绍
  8. JS实现元素的拖动与占位功能
  9. JS实现元素的拖动与占位功能
  10. JavaScript实现搜索的数据显示