【问题标题】:can any Handler post to mainThread using Lopper.getMainLooper()任何处理程序都可以使用 Looper.getMainLooper() 发布到主线程
【发布时间】:2017-05-20 08:21:53
【问题描述】:

假设我在我创建的另一个线程中,在 android 中我执行以下操作:

//this is called from another thread (not mainTread)

new Handler(Lopper.getMainLooper()).post(new Runnable() {  
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });

我是否理解这里的处理程序与线程相关联,但由于我使用的是 mainThreads 循环器,它会将 runnable 发送到 mainThreads 消息队列进行处理?如果这是真的,任何线程上的任何处理程序都可以接受另一个线程循环器发布到它?对吗?

或者是“new Handler(Lopper.getMainLopper())”使它成为一个 mainThread 处理程序?

【问题讨论】:

    标签: android multithreading handler android-looper


    【解决方案1】:

    是的,你没看错。

    1. 一个线程只能有一个唯一的 Looper,并且可以有许多唯一的 Handler 与之关联。
    2. 处理程序通过线程的 Looper 与实例化它的线程隐式关联。此外,您还可以通过在构造函数中传递 Looper 来将您的 Handler 与任何线程绑定。

    我建议看一眼this article 以更好地理解这个问题。

    【讨论】:

      【解决方案2】:

      试试这个...用context.getMainLooper()替换Looper.getMainLooper()。这应该可以。

      new Handler(context.getMainLooper()).post(new Runnable() {  
                          @Override
                          public void run() {
                              mAdapter.notifyDataSetChanged();
                          }
                      });
      

      【讨论】:

      • 我的问题实际上是理论上的。我想知道任何处理程序是否可以简单地通过使用它的 looper 来与任何线程交谈。
      • 如果你可以访问looper那为什么不呢?looper在线程中维护进程队列。
      猜你喜欢
      • 2015-10-27
      • 1970-01-01
      • 2015-08-04
      • 2013-10-09
      • 2020-02-15
      • 2019-01-26
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多