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?
According to the Android Documentation you should call quit().
When you call Looper.loop()
a while loop is started. Calling Looper.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:
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);
}