Error while dispaying an Toast message: Can't create handler inside thread that has not called Looper.prepare()

限于喜欢 提交于 2019-12-21 04:38:11

问题


I am getting an Runtime Exception:Can't create handler inside thread that has not called Looper.prepare() while displaying the Toast message in a worker thread.

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.


回答1:


Define a Handler like 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);


来源:https://stackoverflow.com/questions/7185942/error-while-dispaying-an-toast-message-cant-create-handler-inside-thread-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!