【问题标题】:why can I touch UI in non-uithread by looper?为什么我可以通过looper在非ui线程中触摸UI?
【发布时间】:2014-09-05 07:54:22
【问题描述】:
    thread = new Thread() {
        public void run() {
            super.run();
            System.out.println("run:" + Thread.currentThread().getName());
            Looper.prepare();
            handler = new Handler();
            Looper.loop();
        };
    };
    thread.start();

然后

    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MActivity.this,Thread.currentThread().getName(),0).show();
        }
    });

代码运行正确。

但是吐司显示:“Thread-217”

这意味着 toast 从非 uithread 显示。

为什么?


我很抱歉。我知道答案。 Toast 是一个特殊的 UI 元素。它可以从任何线程显示。但其他 UI 元素,例如 Button TextView 只能在 UI 线程中触摸。 因此,我的代码运行正确,但是当您将 toast 更改为 Button 时,崩溃了。

【问题讨论】:

  • 因为你在后台线程中创建了Handler
  • @pskink 说UI操作必须放在UI Thread上?

标签: android multithreading looper


【解决方案1】:

您正在尝试使用可运行的 UI 线程在 UI 线程中显示 toast,这就是它出错的原因

  Thread background = new Thread(new Runnable() {   
        public void run() {
                         // Send message to handler
                            handler.sendMessage(msgObj);
                        }
      };




      private final Handler handler = new Handler() {
               public void handleMessage(Message msg) {
                  //Catch the response and show the toast
                  String aResponse = msg.getData().getString("message");

                  Toast.makeText(getBaseContext(),"Not Got Response From Server.",
                         Toast.LENGTH_SHORT).show();
                                }
          };

【讨论】:

  • 我的意思是 toast.show() 应该在一个单独的线程上运行。因为处理程序是在那个非 uithread 中创建的。但代码运行正确。所以我们可以在非 uithread 上触摸 UI?
  • 您不应该在非 UI 线程上显示 toast,它肯定会崩溃....Toast 应该始终在 UI 线程中。
【解决方案2】:

您必须在 UiThread 中创建处理程序。处理程序将消息发送到创建它的线程。

handler = new Handler();

thread = new Thread() {
        public void run() {
            super.run();
            System.out.println("run:" + Thread.currentThread().getName());
            Looper.prepare();
            Looper.loop();
        };
    };
    thread.start();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多