天天看點

LeakCanary 使用一

一概要:

LeakCanary是GitHub上著名的開源組織Square貢獻的一個記憶體洩漏自動檢測工具。

優點:自動化發現記憶體洩漏;配置非常的簡單。

缺點:配置時內建到低版本的應用會有bug,這時嘗試修改版本:compileSdkVersion 21。

配置請參考:https://github.com/square/leakcanary

#補充一點:記憶體洩漏往往發生在,生命周期較長的對象,直接或間接的持有了生命周期較短的對象的強引用,導緻

生命周期較短的對象不能及時的釋放。

二使用:

接入步驟:

1,在Gradle中添加依賴(LeakCanary的非常好的一點是,在debug版本時才會檢測,在release版本會跳過檢測)

//leakcanary 檢測記憶體洩漏
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
           

2,在Application中初始化LeakCanary

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();
            if (LeakCanary.isInAnalyzerProcess(this)) {
                // This process is dedicated to LeakCanary for heap analysis.
                // You should not init your app in this process.
                return;
            }
            refWatcher = LeakCanary.install(this);
        }
    }
           

Ok,這樣基本的接入就已經完成了。

這裡為了測試,故意寫一個記憶體洩漏的用法,一個單例SingleTon對象,持有Activity對象。

public class TestLeakSingleton {

    private TextView tv;
    private Context context;

    private static TestLeakSingleton singleton = null;

    public static TestLeakSingleton getInstance(Context context){
        if(singleton == null){
            singleton = new TestLeakSingleton(context);
        }
        return singleton;
    }

    private TestLeakSingleton(Context context){
        this.context = context;
    }

    public void setTvAppName(TextView tv){
        this.tv = tv;
        tv.setText(context.getString(R.string.app_name));
    }
}
           

在Activity中的使用:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testsecond);
        TextView textView = (TextView) findViewById(R.id.tv_appname);
        TestLeakSingleton.getInstance(this).setTvAppName(textView);
    }
           

操作:1,啟動這個Activity;2,退出activity。

結果:看到很多部落格都說,會直接在在通知欄出現相關的通知。我的實際情況是:

1,APP安裝啟動之後,在應用菜單中發現圖示。

LeakCanary 使用一

執行上述操作後出現了一個類似的Toast的彈窗如:

LeakCanary 使用一

2,點選這個Toast中的logo,然後在通知欄才會有相關通知。

LeakCanary 使用一

3,點選通知後就有詳細的說明。(第二方法是直接點選應用菜單中Leaks圖檔,也能進入到此詳情頁)

LeakCanary 使用一

#第一部分:指明TestLeakSingeton的單例模式;

#第二部分:指明造成洩漏的引用context。

#第三部分:指明造成洩漏的類對象。

繼續閱讀