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.
你可以通过传递一个
也是一直都会看到这个问题,但是不知道怎么解决,也不知道它描述的内存泄露的原因。直到有一天突然在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。但是,除非消息队列中有很长时间的延迟消息,否则它不会成为一个严重问题。
相关文章推荐
- Handler 当做内部类,导致内存泄露的问题
- Handler当做内部类,导致内存泄露的问题
- Handler&内部类导致的内存泄露问题
- Android:Handler,内部类导致的可能内存泄露
- Android中Handler使用不当导致内存泄露的问题
- android开发中,可能会导致内存泄露的问题
- android 使用handler内存泄露问题
- Android开发编码规范导致的内存泄露问题
- Android开发编码规范导致的内存泄露问题
- Android开发,中可能会导致内存泄露的问题
- 【转】android开发中,可能会导致内存泄露的问题
- Android InputMethodManager 导致的内存泄露及解决方案
- [置顶] android内存泄漏总结(总结所有导致内存泄露的可能性及解决方案)
- 有关android内存泄露的问题以及解决方案
- android开发中,可能会导致内存泄露的问题
- Android内存溢出与优化(四)——防止Handler导致的内存泄露
- android handler的内存泄露问题
- Android中Handler导致的内存泄露
- Android 中 Handler 引起的内存泄露 在Android常用编程中,Handler在进行异步操作并处理返回结果时经常被使用。其实这可能导致内存泄露,代码中哪里可能导致内存泄露,又是如何
- Android中声名Handler变量的内存泄露问题