android排查内存泄露,Android内存泄漏排查利器LeakCanary

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

在 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图标。

3f2f7a7e1d10e58a60db8b120dff22b3.png

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

76b0983ffe571d9445c2f787a832a872.png

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

6d642c76c2beb1dc821f9bd62eff5e0d.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值