How to use Leak Canary

后端 未结 5 1733
悲&欢浪女
悲&欢浪女 2020-12-24 05:57

I know this is probably a dumb question, but I am pretty new at developing android, and I currently experiencing an OutOfMemoryError in my apps, which I have tried to debug

5条回答
  •  一个人的身影
    2020-12-24 06:40

    The nice thing about leak canary is how automated it works. By default, it already "watches" for activities that are not being properly GCed. So out of the box, if any activity is leaking you should receive the notification.

    On my project I've added an extra method on the Application like this:

    public class ExampleApplication extends Application {
        public static ExampleApplication instance;
        private RefWatcher refWatcher;
    
        @Override
        public void onCreate() {
            super.onCreate();
            instance = this;
            refWatcher = LeakCanary.install(this);
        }
    
        public void mustDie(Object object) {
            if (refWatcher != null) {
                refWatcher.watch(object);
            }
        }
    }
    

    so the important stuff with garbage collection and memory leak and canary is to know when stuff should be collected and ask that item to be watched.

    For for example we're using a "base fragment" with the following code:

    @Override
    public void onDestroy() {
        super.onDestroy();
        ExampleApplication.instance.mustDie(this);
    }
    

    this way LeakCanary is trying to check if any fragment is leaking memory.

    So for you to further implement on your app, you could/should on tasks or instances that you know it should be garbage collected but you think it might not be, and you're not sure where, you can call that too: ExampleApplication.instance.mustDie(object);

    and then you MUST run the application and rotate the device and force the leak to happen, so leak canary can grab/analyse the stack trace and give you valuable information on how to fix it.

    I hope it helps.

提交回复
热议问题