Android内存泄漏排查LeakCanary Android内存泄漏排查利器LeakCanary

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android内存泄漏排查LeakCanary Android内存泄漏排查利器LeakCanary

Panda Fang   2021-03-24 我要评论
想了解Android内存泄漏排查利器LeakCanary的相关内容吗,Panda Fang在本文为您仔细讲解Android内存泄漏排查LeakCanary的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,内存泄漏,LeakCanary,下面大家一起来学习吧。

本文为大家分享了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<Void, Void, Void>() {
  @Override protected Void doInBackground(Void... params) {
  // Do some slow work in background
  SystemClock.sleep(20000);
  return null;
  }
 }.execute();
 }
}

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

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

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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们