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

时间:2011-08-25 06:23:12

标签: android exception toast

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

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

应该采取什么方法来避免这种情况。

1 个答案:

答案 0 :(得分:15)

定义一个像这样的处理程序:

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

然后将以下代码放在需要显示吐司信息的位置。

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