温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Android中利用LeakCanary对内存泄漏进行排查

发布时间:2020-11-30 16:49:15 来源:亿速云 阅读:144 作者:Leah 栏目:移动开发

今天就跟大家聊聊有关怎么在Android中利用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图标。

看完上述内容,你们对怎么在Android中利用LeakCanary对内存泄漏进行排查有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI