LeakCanary使用手冊

demo

一個很是簡單的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demojava

開始使用

在 build.gradle 中加入引用,不一樣的編譯使用不一樣的引用:android

dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
 }

在 Application 中:git

public class ExampleApplication extends Application { 
 
    

  @Override public void onCreate() { 
 
    
    super.onCreate();
    LeakCanary.install(this);
  }
}

這樣,就萬事俱備了! 在 debug build 中,若是檢測到某個 activity 有內存泄露,LeakCanary 就是自動地顯示一個通知。github

爲何須要使用 LeakCanary?

問得好,看這個文章LeakCanary: 讓內存泄露無所遁形服務器

如何使用

使用 RefWatcher 監控那些本該被回收的對象。app

RefWatcher refWatcher = {...};

// 監控
refWatcher.watch(schrodingerCat);

LeakCanary.install() 會返回一個預約義的 RefWatcher,同時也會啓用一個 ActivityRefWatcher,用於自動監控調用Activity.onDestroy() 以後泄露的 activity。eclipse

public class ExampleApplication extends Application { 
 
    

  public static RefWatcher getRefWatcher(Context context) { 
 
    
    ExampleApplication application = (ExampleApplication) context.getApplicationContext();
    return application.refWatcher;
  }

  private RefWatcher refWatcher;

  @Override public void onCreate() { 
 
    
    super.onCreate();
    refWatcher = LeakCanary.install(this);
  }
}

使用 RefWatcher 監控 Fragment:ide

public abstract class BaseFragment extends Fragment { 
 
    

  @Override public void onDestroy() { 
 
    
    super.onDestroy();
    RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
    refWatcher.watch(this);
  }
}

工做機制

  1. RefWatcher.watch() 建立一個 KeyedWeakReference 到要被監控的對象。post

  2. 而後在後臺線程檢查引用是否被清除,若是沒有,調用GC。gradle

  3. 若是引用仍是未被清除,把 heap 內存 dump 到 APP 對應的文件系統中的一個 .hprof 文件中。

  4. 在另一個進程中的 HeapAnalyzerService 有一個 HeapAnalyzer 使用HAHA 解析這個文件。

  5. 得益於惟一的 reference key, HeapAnalyzer 找到 KeyedWeakReference,定位內存泄露。

  6. HeapAnalyzer 計算 到 GC roots 的最短強引用路徑,並肯定是不是泄露。若是是的話,創建致使泄露的引用鏈。

  7. 引用鏈傳遞到 APP 進程中的 DisplayLeakService, 並以通知的形式展現出來。

如何複製 leak trace?

在 Logcat 中,你能夠看到相似這樣的 leak trace:

In com.example.leakcanary:1.0:1 com.example.leakcanary.MainActivity has leaked:

* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #1')
* references com.example.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)
* leaks com.example.leakcanary.MainActivity instance

* Reference Key: e71f3bf5-d786-4145-8539-584afaecad1d
* Device: Genymotion generic Google Nexus 6 - 5.1.0 - API 22 - 1440x2560 vbox86p
* Android Version: 5.1 API: 22
* Durations: watch=5086ms, gc=110ms, heap dump=435ms, analysis=2086ms

你甚至能夠經過分享按鈕把這些東西分享出去。

SDK 致使的內存泄露

隨着時間的推移,不少SDK 和廠商 ROM 中的內存泄露問題已經被儘快修復了。可是,當這樣的問題發生時,通常的開發者能作的事情頗有限。

LeakCanary 有一個已知問題的忽略列表,AndroidExcludedRefs.java,若是你發現了一個新的問題,請提一個 issue 並附上 leak trace, reference key, 機器型號和 SDK 版本。若是能夠附帶上 dump 文件的 連接那就再好不過了。

對於最新發布的 Android,這點尤爲重要。你有機會在幫助在早期發現新的內存泄露,這對整個 Android 社區都有極大的益處。

開發版本的 Snapshots 包在這裏: Sonatype's snapshots repository

leak trace 以外

有時,leak trace 不夠,你須要經過 MAT 或者 YourKit 深挖 dump 文件。

經過如下方法,你能找到問題所在:

  1. 查找全部的 com.squareup.leakcanary.KeyedWeakReference 實例。
  2. 檢查 key 字段
  3. Find the KeyedWeakReference that has a key field equal to the reference key reported by LeakCanary.
  4. 找到 key 和 和 logcat 輸出的 key 值同樣的 KeyedWeakReference
  5. referent 字段對應的就是泄露的對象。
  6. 剩下的,就是動手修復了。最好是檢查到 GC root 的最短強引用路徑開始。

自定義

UI 樣式

DisplayLeakActivity 有一個默認的圖標和標籤,你只要在你本身的 APP 資源中,替換如下資源就可。

res/
  drawable-hdpi/
    __leak_canary_icon.png
  drawable-mdpi/
    __leak_canary_icon.png
  drawable-xhdpi/
    __leak_canary_icon.png
  drawable-xxhdpi/
    __leak_canary_icon.png
  drawable-xxxhdpi/
    __leak_canary_icon.png
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="__leak_canary_display_activity_label">MyLeaks</string>
</resources>

保存 leak trace

DisplayLeakActivity saves up to 7 heap dumps & leak traces in the app directory. You can change that number by providingR.integer.__leak_canary_max_stored_leaks in your app:

在 APP 的目錄中,DisplayLeakActivity 保存了 7 個 dump 文件和 leak trace。你能夠在你的 APP 中,定義R.integer.__leak_canary_max_stored_leaks 來覆蓋類庫的默認值。

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <integer name="__leak_canary_max_stored_leaks">20</integer>
</resources>

上傳 leak trace 到服務器

你能夠改變處理完成的默認行爲,將 leak trace 和 heap dump 上傳到你的服務器以便統計分析。

建立一個 LeakUploadService, 最簡單的就是繼承 DisplayLeakService :

public class LeakUploadService extends DisplayLeakService { 
 
    
  @Override
  protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) { 
 
    
    if (!result.leakFound || result.excludedLeak) { 
 
    
      return;
    }
    myServer.uploadLeakBlocking(heapDump.heapDumpFile, leakInfo);
  }
}

請確認 release 版本 使用 RefWatcher.DISABLED

public class ExampleApplication extends Application { 
 
    

  public static RefWatcher getRefWatcher(Context context) { 
 
    
    ExampleApplication application = (ExampleApplication) context.getApplicationContext();
    return application.refWatcher;
  }

  private RefWatcher refWatcher;

  @Override public void onCreate() { 
 
    
    super.onCreate();
    refWatcher = installLeakCanary();
  }

  protected RefWatcher installLeakCanary() { 
 
    
    return RefWatcher.DISABLED;
  }
}

自定義 RefWatcher

public class DebugExampleApplication extends ExampleApplication { 
 
    
  protected RefWatcher installLeakCanary() { 
 
    
    return LeakCanary.install(app, LeakUploadService.class);
  }
}

別忘了註冊 service:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    >
  <application android:name="com.example.DebugExampleApplication">
    <service android:name="com.example.LeakUploadService" />
  </application>
</manifest>本文來自LeakCanary中文官方文檔

本文同步分享在 博客「xiangzhihong8」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索