Android記憶體流失排查利器LeakCanary,androidleakcanary
開源地址: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表徵圖。
點進去就會看到記憶體流失記錄
再點進去就可以看到調用棧了