本文為大家分享了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圖標。

點進去就會看到內存泄漏記錄

再點進去就可以看到調用棧了

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答