天天看點

第二十四篇 Android記憶體洩露與檢測

一、記憶體洩露與記憶體溢出的差別.

記憶體洩露:程式在向系統申請配置設定記憶體空間後(new),在使用完畢後未釋放。結果導緻一直占據該記憶體單元,我們和程式
都無法再使用該記憶體單元,直到程式結束,這是記憶體洩露。(洩露原因:無用對象,但可到達)

記憶體溢出:程式向系統申請的記憶體空間超出了系統能給的。比如記憶體隻能配置設定一個int類型,我卻要塞給他一個long類型,
系統就出現oom。又比如一車最多能坐5個人,你卻非要塞下10個,車就擠爆了。

大量的記憶體洩露會導緻記憶體溢出(oom)。
           

二、使用LeakCanary檢測記憶體是否洩露.

1.在module的build.gradle中的dependencies加入:

    debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseImplementation 'com.squareup.leakcanary:leakcanary-android:1.5'
    testImplementation 'com.squareup.leakcanary:leakcanary-android:1.5'

2.在自定義的Applicaton中加入:

    private RefWatcher refWatcher;

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

    private RefWatcher setupLeakCanary() {
            if (LeakCanary.isInAnalyzerProcess(this)) {
                return RefWatcher.DISABLED;
        }
            return LeakCanary.install(this);
        }

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

3.在AndroidManifest.xml中注冊自定義的Application即可。
           

三、內建LeakCanary後,出現記憶體洩漏會在通知欄出現記憶體洩漏資訊,如下圖:

第二十四篇 Android記憶體洩露與檢測
注意:真機上測試沒有出現在通知欄上,而是直接在手機桌面有個圖示,點選進去就可以檢視記憶體洩漏資訊了。
           

點選詳情後,就可以 檢視具體記憶體洩漏資訊,如下圖:

第二十四篇 Android記憶體洩露與檢測