您的位置:首页 > 移动开发 > Android开发

Android Handler当做内部类,导致内存泄露的问题解决方案

2018-02-27 16:54 597 查看
你用android studio编译你的项目的时候可曾遇到过这个问题,如果有的话,这篇文章会给你解决方法。
也是一直都会看到这个问题,但是不知道怎么解决,也不知道它描述的内存泄露的原因。直到有一天突然在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。但是,除非消息队列中有很长时间的延迟消息,否则它不会成为一个严重问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息