我得到一个运行时异常:在工作线程中显示Toast消息时,无法在未调用Looper.prepare()的线程内创建处理程序.
我有一个服务(在远程进程中运行),它创建一个对象.该对象负责连接到线程中的服务器.我得到了服务器的响应.我想在toast中显示来自服务器的消息.那时我得到了这个例外.我尝试使用handler.post在Handler中发布它.但我仍然得到例外.
应该采取什么方法来避免这种情况.
解决方法
像这样定义一个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();
- }
- }
- Message msg = handler.obtainMessage();
- msg.arg1 = 1;
- handler.sendMessage(msg);