14

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

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

4

3 回答 3

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);
}
于 2010-09-20T16:56:45.647 回答
0

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

但是如果你只是将这个单行添加到你的 onDestroy() 方法中,真的没有缺点吗?

于 2010-05-08T13:34:05.410 回答
0

添加到 Jonathan 的上述答案,请在quit()quitSafely()之间明智地选择,因为 quit()终止而不处理消息队列中的任何更多消息,因为一旦消息队列中的所有剩余消息退出,quitSafely() 就会立即终止已到期交付 已处理

于 2018-09-29T06:08:32.420 回答