Android:退出 Looper?

Posted

技术标签:

【中文标题】Android:退出 Looper?【英文标题】:Android: Quitting the Looper? 【发布时间】:2011-02-17 02:30:09 【问题描述】:

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

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

【问题讨论】:

【参考方案1】:

根据android Documentation,你应该调用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);

【讨论】:

【参考方案2】:

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

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

【讨论】:

除了几个处理器周期之外没有任何缺点。但我喜欢了解系统在幕后工作的细微差别。【参考方案3】:

除了上面的 answer 乔纳森,请在 quit() 和 quitSafely() 之间明智地选择作为 quit() 终止而不处理 消息队列中的任何更多消息作为 quitSafely() 在处理完消息队列中所有剩余的消息后立即终止

【讨论】:

以上是关于Android:退出 Looper?的主要内容,如果未能解决你的问题,请参考以下文章

Android的Handler,Looper源码剖析

Android中的Looper类

Android中的Looper类

[Android源代码分析]Android消息机制,Handler,Message,Looper,MessageQueue

Android消息机制——Handler

Android源码学习 Handler之Looper