Android在thread中Toast不能显示问题解决

2018-01-26 01:05:22

有两种方法,我用第一种方法,软件假死了。所以不推荐。

第一种方法:

改写代码之前是:


[java] view plain copy

  1. Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();  

改写之后:


[java] view plain copy

  1. Looper.prepare();  

  2. Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();  

  3. Looper.loop();  


一般如果不是在主线程中又开启了新线程的话,一般都会碰到这个问题。

原因是在创建新线程的时候默认情况下不会去创建新的MessageQueue。


第二种方法:

[java] view plain copy

  1. Handler handler = new Handler() {  

  2.     @Override  

  3.     public void handleMessage(Message msg) {  

  4.         // TODO Auto-generated method stub  

  5.         if (msg.what == 0) {  

  6.             Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();  

  7.         }  

  8.         super.handleMessage(msg);  

  9.     }  

  10.   

  11. };  

  12. Message msg = handler.obtainMessage();  

  13. msg.what = 0;  

  14. handler.sendMessage(msg);  






线程里面不能进行UI操作的,可以在线程里面用handler发送信息,然后再显示UI,比如就把你的toast改成handler.sendEmptyMessage()。。


  • 2017-11-10 00:06:15

    CORS: credentials mode is 'include'

    XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

  • 2017-11-19 00:17:51

    Java如何获取Date的“昨天”与“明天”示例代码

    最近在做项目的时候用到Date和Calendar比较多,而且用到的方式也比较全,突然想到一个问题,Java如何获取Date的"昨天"与"明天",也就是前一天和后一天呢?思考后写出了方法,想着万一以后用到,就总结出来,也方便有需要的朋友们参考借鉴,下面来一起看看吧。

  • 2017-11-23 02:00:51

    js 分页插件twbs-pagination

    ​cdn地址 http://www.bootcdn.cn/twbs-pagination/ 官网地址 可以在cdn地址上面查看到