LeakCanary Android 和 Java 記憶體泄露檢測。

來源:互聯網
上載者:User

標籤:

開始使用

在 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); }}


如何使用

使用 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, 並以通知的形式展示出來。

LeakCanary Android 和 Java 記憶體泄露檢測。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.