LeakCanary 中文使用說明

LeakCanary

Android 和 Java 內存泄露檢測。

“A small leak will sink a great ship.” - Benjamin Franklin

千里之堤, 毀於蟻穴。 -- 《韓非子·喻老》



demo: https://github.com/liaohuqiu/leakcanary-demo

開始使用

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

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

在 Application 中:

public class ExampleApplication extends Application {

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

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

爲什麼需要使用 LeakCanary?

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

如何使用

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

RefWatcher refWatcher = {...};

// 監控
refWatcher.watch(schrodingerCat);

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

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:

public abstract class BaseFragment extends Fragment {

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

工作機制

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

  2. 然後在後臺線程檢查引用是否被清除,如果沒有,調用GC。

  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>

源文:http://www.liaohuqiu.net/cn/posts/leak-canary-read-me/

LeakCanary 中文使用說明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章