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?
To kill it you must quit the loop. To do that, you need to run the quit command on the context of that thread. And don't forget to null all reference to views and activities.
Be sure to call quit() to end the loop. Quits the looper. Causes the loop() method to terminate without processing any more messages in the message queue.
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.
Looper is an abstraction over event loop (infinite loop which drains queue with events) and Handler is an abstraction to put/remove events into/from queue with events (which is drained by Looper) and handle these events when they are processed.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With