也是一直都会看到这个问题,但是不知道怎么解决,也不知道它描述的内存泄露的原因。直到有一天突然在statck-overflow上看见了.
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.Callback
构造函数来避免Lint警告Handler
(也就是说,你不需要子类Handler
并且没有Handler
非静态的内部类)
Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
}
});
据我了解,这不会避免潜在的内存泄漏。Message
对象持有对mHandler
持有引用的Handler.Callback
对象的引用,该对象持有对对象的引用。只要Looper
消息队列中有消息,就不会是GC。但是,除非消息队列中有很长时间的延迟消息,否则它不会成为一个严重问题。