Android: Quitting the Looper? Android: Quitting the Looper? multithreading multithreading

Android: Quitting the Looper?


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);}


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?


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