支付 Toast 消息时出错:无法在未调用 Looper.prepare() 的线程中创建处理程序



我在一个工作线程中得到一个Runtime Exception:Can't create handler inside thread that has not called Looper.prepare() while displaying the Toast message

我有一个创建对象的服务(在远程进程中运行)。该对象负责在线程中连接到服务器。我从服务器得到响应。我想在toast中显示来自服务器的消息。那时我得到了这个例外。我试图通过使用Handler .post在处理程序中发布它。但是我仍然得到异常。

定义一个Handler:

 private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
              if(msg.arg1 == 1)
                    Toast.makeText(getApplicationContext(),"Your message", Toast.LENGTH_LONG).show();
        }
    }

然后将下面的代码放在需要显示toast消息的地方。

Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);

相关内容

最新更新