views:

462

answers:

2

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?

A: 

I don't now the correct answer but judging from the serveral documentations and tutorials i've seen in the Internet, none of them calls handler.getLopper().quit(). So i would guess that is not necessary to do this explicitly.

But there is no really drawback if you just add this onliner to you onDestroy() method?

Roflcoptr
No drawback beyond a few processor cycles. But I like to understand the nuances of how the system is working behind the scenes.
stormin986
+2  A: 

According to the Android Documentation you should call quit().

When you call Looper.loop() a while loop is started. Calling Looper.quit() causes the while 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);
}
Jonathan
I can confirm that this works.
Lars D