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

Shr*_*aya 8 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中发布它.但我仍然得到例外.

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

jai*_*nal 15

像这样定义一个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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后将以下代码放在需要显示Toast消息的位置.

Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
Run Code Online (Sandbox Code Playgroud)