Android內存泄漏排查利器LeakCanary
本文為大家分享了Android內存泄漏排查利器,供大家參考,具體內容如下
開源地址: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 ,如果沒有就創(chuàng)建一個,繼承 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); // 你的其他代碼從下面開始 } }
官方已經(jīng)有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次的話泄漏規(guī)模太小,可能不會探測到。LeakCanary 一旦探測到會彈出提示的。
回到桌面,會看到一個LeakCanary 的圖標,如果有多個app 用到就會有多個LeakCanary圖標。
點進去就會看到內存泄漏記錄
再點進去就可以看到調用棧了
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android使用AlertDialog實現(xiàn)對話框
本文主要介紹了Android使用AlertDialog實現(xiàn)對話框的相關知識,具有很好的參考價值。下面跟著小編一起來看下吧2017-03-03詳解Android 語音播報實現(xiàn)方案(無SDK)
本篇文章主要介紹了詳解Android 語音播報實現(xiàn)方案(無SDK),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11Android 深入探究自定義view之事件的分發(fā)機制與處理詳解
對于安卓程序員來說,自定義view簡直不要太重要,畢竟有很多功能,譬如圓形頭像這些,用單純的原生非常難以實現(xiàn),而用自定義view,簡直分分鐘2021-11-11Android 中圖片和按鈕按下狀態(tài)變化實例代碼解析
這篇文章通過實例代碼給大家總結了android 中圖片和按鈕按下狀態(tài)變化問題,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨腳本之家小編一起學習吧2018-06-06