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图标。

这里写图片描述

点击该图标进去就可以看到相应的记录。

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