【面试题】handler内存泄露的根本原因是?

2019-01-23  本文已影响0人  小浩_w

This Handler class should be static or leaks might occur (anonymous android.os.Handler) less... (Ctrl+F1)
Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

简单翻译如下:

由于handler定义为内部类,可能会阻止GC。如果handler的Looper或MessageQueue 非主线程,那么没有问题。如果handler的Looper或MessageQueue 在主线程,那么需要按如下定义:定义handler为静态内部类,当你实例化handler的时候,传入一个外部类的弱引用,以便通过弱引用使用外部类的所有成员。

handler导致activity内存泄露的原因:

handler发送消息在当前handler的消息队列中,如果这个时候activity finish(),
那么消息队列里的消息依旧会由handler进行处理,如果此时handler声明为内部类(非静态),内部类持有外部类的实例引用,那么就会导致activity无法回收,所以导致activity泄漏内存

为何handler要定义为static?

因为静态内部类不持有外部类的引用,所以使用静态的handler不会导致activity的泄露

为何handler要定义为static的同时,还要用WeakReference 包裹外部类的对象?

以便通过弱引用使用外部类的所有成员。

避免handle内存泄露的办法
上一篇 下一篇

猜你喜欢

热点阅读