Android:退出Looper?

sto*_*986 14 multithreading android message-queue handler

我有一个线程,我用来定期更新我的Activity中的数据.我创建线程并启动一个looper以使用处理程序postDelay().在我的活动的onDestroy()中,我在我的处理程序上调用removeCallbacks().

我应该打电话handler.getLooper().quit()吗?或者不用担心它,让操作系统处理它?或者它会永远运行,消耗CPU周期?

Jon*_*han 18

根据Android文档,您应该调用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);
}
Run Code Online (Sandbox Code Playgroud)


小智 0

我现在不知道正确的答案,但从我在互联网上看到的几个文档和教程来看,它们都没有调用 handler.getLooper().quit()。所以我猜想没有必要明确地这样做。

但是,如果您只是将这一行代码添加到 onDestroy() 方法中,真的没有任何缺点吗?

  • 除了几个处理器周期之外没有任何缺点。但我喜欢了解系统在幕后如何工作的细微差别。 (3认同)