Android記憶體流失排查利器LeakCanary,androidleakcanary

來源:互聯網
上載者:User

Android記憶體流失排查利器LeakCanary,androidleakcanary

開源地址: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 ,如果沒有就建立一個,繼承 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);        // 你的其他代碼從下面開始    }}

官方已經有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次的話泄漏規模太小,可能不會探測到。LeakCanary  一旦探測到會彈出提示的。

回到案頭,會看到一個LeakCanary 的表徵圖,如果有多個app 用到就會有多個LeakCanary表徵圖。

 點進去就會看到記憶體流失記錄

 

再點進去就可以看到調用棧了

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.