我有一個線程用於定期更新我的活動中的數據。我創建了線程並啓動了一個使用postDelay()
的處理程序的活套。在我的活動onDestroy()中,我在我的處理程序上調用removeCallbacks()。Android:退出Looper?
我應該打電話給handler.getLooper().quit()
嗎?或者不用擔心,讓操作系統處理它?或者它會一直運行,消耗CPU週期?
我有一個線程用於定期更新我的活動中的數據。我創建了線程並啓動了一個使用postDelay()
的處理程序的活套。在我的活動onDestroy()中,我在我的處理程序上調用removeCallbacks()。Android:退出Looper?
我應該打電話給handler.getLooper().quit()
嗎?或者不用擔心,讓操作系統處理它?或者它會一直運行,消耗CPU週期?
我現在不正確的答案,但是從幾個文檔和教程我已經看到了互聯網上來看,他們都不叫handler.getLooper()。退出()。所以我想這是沒有必要明確地做到這一點。
但是,如果您只是將這一行添加到您的onDestroy()方法,那麼真的沒有缺點嗎?
根據Android Documentation你應該調用quit()。
當您撥打Looper.loop()
while循環啓動。調用Looper.quit()
會導致循環終止。垃圾收集器無法在循環執行時收集對象。
下面是Looper.java相關部分:
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // might block
//if (!me.mRun) {
// break;
//}
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!= null) me.mLogging.println(
">>>>> Dispatching to " + msg.target + " "
+ msg.callback + ": " + msg.what
);
msg.target.dispatchMessage(msg);
if (me.mLogging!= null) me.mLogging.println(
"<<<<< Finished to " + msg.target + " "
+ msg.callback);
msg.recycle();
}
}
}
public void quit() {
Message msg = Message.obtain();
// NOTE: By enqueueing directly into the message queue, the
// message is left with a null target. This is how we know it is
// a quit message.
mQueue.enqueueMessage(msg, 0);
}
我可以證實,這個工程。 – 2010-10-06 20:01:57
沒有缺點,除了一些處理器週期。但是,我想了解系統是如何在幕後工作的細微之處。 – stormin986 2010-05-09 00:32:54