【问题标题】:Posting to Handler tied to current thread发布到绑定到当前线程的处理程序
【发布时间】:2015-02-19 23:00:46
【问题描述】:

我有一个处理程序,mHandler,绑定到主线程。 mHandler 位于 Service 中。假设我现在从主线程中将Runnable 发布到mHandler,如下所示:

public class SomeService extends Service {
    // Handler is created on the main thread
    // (and hence it is tied to the main thread)
    private Handler mHandler = new Handler();

    @Override
    public void onDestroy() {
        // onDestroy runs on the main thread
        // Is the code in this Runnable processed right away?
        mHandler.post(new Runnable() {
            // (Some code statements that are to be run on the main thread)
            ...
        });
        super.onDestroy();
    }
}

我知道这个例子有点傻,因为Handler 是不必要的。但是,这是这个问题的一个很好的例子。

现在我的问题是:

  1. Runnable 中的代码语句是否会被立即处理,因为发布Runnable 的线程也是处理Runnable 的线程?还是因为Handler 在内部使用MessageQueue 并因此可能有Runnables 发布到其他地方的Handler(在我的Runnable 之前到达),所以它的工作方式不同?
  2. 此外,语句是否可能永远不会运行,因为post(Runnable r) 是一个异步调用,因此onDestroy() 将完成并且Service 将在Handler 开始运行之前被系统杀死代码。

提前谢谢你。

【问题讨论】:

    标签: android android-handler


    【解决方案1】:
      1234563 /p>
    1. 同样,由于Service 并不意味着一个不同的线程,对onDestroy 的调用并不意味着Handler 的线程已被终止。在本例中,您将发布到主循环器,并且该线程一直处于活动状态,直到应用程序进程终止。

    【讨论】:

    • 比起Handler的线程,我更关心服务的生命周期。我假设随着 onDestroy() 完成,服务和处理程序现在已经死了,因此可以免费进行垃圾收集。现在如果在调度 Runnable 之前清除服务,我假设 Runnable 永远不会运行...?
    • 如果您要发布到主循环器的队列,主循环器持有对其队列的引用(处理程序会将可运行对象代理到该队列),因此您的可运行对象在执行之前将无法获得 GC。
    • 并且由于 Handler 是服务的一部分,服务也会保持活动状态?
    • 没有。 onDestroy 表示服务已经被销毁。
    猜你喜欢
    • 2015-10-27
    • 2010-11-30
    • 2019-11-18
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多