Android重新學習筆記和心得(二):LeakCanary學習

最近新學一個東西,叫LeakCanary,是square公司的產品,square公司出了很多的開源工具,比如:RxJava,Bufferknife等。

總結一下LeakCanary主要是檢測應用有沒有內存泄漏,然後使用MAT工具轉換,並且把泄露的地方指示出來。

源碼的下載地址: git clone [email protected]:square/leakcanary.git

下載之後,導入工程,選在leakcanary-sample安裝即可。(注意默認的例子中,

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() //
        .detectAll() //
        .penaltyLog() //
        .penaltyDialog() //   這裏原來寫的是penaltyDeath,改爲penaltyDialog;否則會直接掛掉
        .build());)

如果是想在自己的項目中導入:

dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.1'
  releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1'
  // Optional, if you use support library fragments:
  debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.1'
}

然後一般在application的onCreate中添加

public class ExampleApplication 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);
    // Normal app init code...
  }
}

默認安裝後,需要到應用管理中把所有的權限都打開,有存儲權限、通知彈出的權限,還要允許通知的彈出,默認都是關閉的。

最後說一下,該檢測工具的原理,有點兒類似獲取ReferenceQueue,這個是java的一個特殊的類,回收時會把所有的將要回收的內容放入該queue中,可以從queue中打印出當前正在回收的對象。所以該檢測工具可能可以通過檢測該變量,查看是否有沒有回收的內容,有的話就默認生成hprof文件,然後使用mat工具轉化,並將獲取出來得內容展示出來。

以上主要參考自:

https://www.jianshu.com/p/73260a46291c   ReferenceQueue的使用

https://blog.csdn.net/sinat_20059415/article/details/79392633 

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