android Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread that has not called

2018-01-26 00:16:33

android Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread that has not called

仔细检查了代码,不应该异常啊??  没有 handler相关代码啊?

               原来是在子线程弹Toast了, 切记,Toast只能在UI线程弹出,如果一定要在子线程弹,那么就通过 new Handler(Looper.getMainLooper()) 来弹



[java] view plain copy

  1. private void toastTest() {  

  2.     new Thread(new Runnable() {  

  3.   

  4. @Override  

  5. public void run() {  

  6.     <span style="color:#cc0000;">Handler handler = new Handler(Looper.getMainLooper());</span>  

  7.     handler.post(new Runnable() {  

  8.           

  9.         @Override  

  10.         public void run() {  

  11.             //放在UI线程弹Toast  

  12.             Toast.makeText(MainActivity.this"toast in work thread", Toast.LENGTH_LONG).show();  

  13.         }  

  14.     });  

  15.     //此处会发生异常  

  16.             Toast.makeText(MainActivity.this"toast in work thread", Toast.LENGTH_LONG).show();  

  17. }  

  18. ).start();  

  19.  }  



  • 2017-02-24 16:53:58

    PHP 中的Closure

    Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的。匿名函数就是没有定义名字的函数。这点牢牢记住就能理解匿名函数的定义了。

  • 2017-03-02 09:45:27

    动态加载js和css

    开发过程中经常需要动态加载js和css,今天特意总结了一下常用的方法。