Android:退出 Looper?
我有一个线程,用于定期更新活动中的数据。我创建了线程并启动了一个循环程序,以便通过 postDelay()
使用处理程序。在我的活动的 onDestroy() 中,我在处理程序上调用removeCallbacks()。
然后我应该调用handler.getLooper().quit()吗?或者不担心它并让操作系统处理它?或者它会永远运行,消耗 CPU 周期?
I have a thread I use to periodically update the data in my Activity. I create the thread and start a looper for using a handler with postDelay()
. In onDestroy() for my activity, I call removeCallbacks() on my handler.
Should I then call handler.getLooper().quit()
? Or not worry about it and let the OS deal with it? Or would it just run forever then, consuming CPU cycles?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
添加到上述 Jonathan 的答案中,请在 quit() 和 quitSafely() as quit() 终止而不处理消息队列中的任何更多消息,其中 as quitSafely() < strong>一旦处理完消息队列中已到期的所有剩余消息就终止
Adding to the above answer by Jonathan, please choose wisely between quit() and quitSafely() as quit() terminate without processing any more messages in the message queue where as quitSafely() terminates as soon as all remaining messages in the message queue that are already due to be delivered have been handled
我现在不知道正确的答案,但从我在互联网上看到的几个文档和教程来看,它们都没有调用 handler.getLooper().quit()。所以我猜想没有必要明确地这样做。
但是,如果您只是将这一行代码添加到 onDestroy() 方法中,真的没有任何缺点吗?
I don't now the correct answer but judging from several documentations and tutorials i've seen on the Internet, none of them call handler.getLooper().quit(). So i would guess that is not necessary to do this explicitly.
But there really is no drawback if you just add this one-liner to your onDestroy() method?
根据 Android 文档 你应该调用 quit() 。
当你调用
Looper.loop()
时,就会启动一个while循环。调用 Looper.quit() 会导致循环终止。当循环执行时,垃圾收集器无法收集您的对象。以下是 Looper.java 中的相关部分:
According to the Android Documentation you should call quit().
When you call
Looper.loop()
a while loop is started. CallingLooper.quit()
causes the loop to terminate. The garbage collector cannot collect your object while the loop is executing.Here are the relevant section from Looper.java: