Android性能提升之LeakCanary

LeakCanary
內存泄漏排查工具

在build.grade 里加上依賴

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'
}

LeakCanary 初始化。 一般在Application中執行

public class YouApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //LeakCanary 初始化
        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);
    }
}

在mainAcitvity中測試下

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圖標。

這裏寫圖片描述

點擊該圖標進去就可以看到相應的記錄。

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