Android解决Can't create handler inside thread that has not called Looper.prepare()

版权声明:本文为DmrfCoder原创作品,如有转载请注明出处 https://blog.csdn.net/qq_36982160/article/details/82351527

在Android子线程中使用Toast时会报错:

  • 代码:
Toast.makeText(this, "", Toast.LENGTH_LONG) .show();
  • 报错:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  • 解决方案:

    方案一:增加Looper.prepare();

    Looper.prepare();
    Toast.makeText(this, "", Toast.LENGTH_LONG) .show();
    Looper.loop();// 进入loop中的循环,查看消息队列

    方案二:post 给主线程去处理

    mainHandler.post(new Runnable() {
    
     @Override
     public void run() {
        if (toast == null) {
           toast = Toast.makeText(context, "",     Toast.LENGTH_SHORT);
    }
    toast.setText(msg);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.show();
     }
    });

猜你喜欢

转载自blog.csdn.net/qq_36982160/article/details/82351527
今日推荐