支付Toast消息时发生错误:无法在未调用Looper.prepare()的线程内创建处理程序 [英] Error while dispaying an Toast message: Can't create handler inside thread that has not called Looper.prepare()
问题描述
我遇到了运行时异常:无法在工作线程中显示Toast消息的同时在未调用Looper.prepare()的线程内创建处理程序
。
我有一个创建对象的服务(在远程进程中运行)。该对象负责在线程中连接到服务器。我得到服务器的回应。我想在吐司中显示来自服务器的消息。当时我得到了这个例外。我尝试通过使用handler.post将其发布到Handler中。但是我还是遇到了例外。
I have a service (runs in a remote process) which creates an object. This object is responsible for connecting to a server in a thread. I get the response from the sever. I want to display the message from the server in the toast. At that time I getting this exception. I tried posting it in a Handler by using handler.post. But still i am getting the exception.
应该采取什么措施来避免这种情况。
What should be the approach to avoid this.
推荐答案
定义这样的处理程序:
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
Toast.makeText(getApplicationContext(),"Your message", Toast.LENGTH_LONG).show();
}
}
然后将以下代码放在需要显示代码的位置
Then put the following code where you need to show your toast message.
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
这篇关于支付Toast消息时发生错误:无法在未调用Looper.prepare()的线程内创建处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!