我在工作线程中得到Runtime Exception:Can't create handler inside thread that has not called Looper.prepare() while displaying the Toast message
。
我有一个服务(在远程进程中运行),它创建了一个对象。该对象负责连接到线程中的服务器。我得到了服务器的响应。我想在toast中显示来自服务器的消息。那时我得到了这个例外。我尝试使用handler.post在Handler中发布它。但我仍然是例外。
应该采取什么方法来避免这种情况。
答案 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);