【Android】报错:Can't create handler inside thread that has not called Looper.prepare()

本文介绍了在Android开发中遇到的错误:Can't create handler inside thread that has not called Looper.prepare()。该错误发生在尝试在子线程中修改UI时,因为Android的UI操作必须在主线程进行。解决方法包括在子线程中手动调用Looper.prepare()和Looper.loop(),或者使用Handler的构造方法传入主线程的Looper。此外,还提到了在AsyncTask中处理UI更新的方法。
摘要由CSDN通过智能技术生成

Toast.makeText(mContext, "msg", Toast.LENGTH_SHORT).show();

在子线程里创建 Toast 时出现报错:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare().
在没有调用 Looper.prepare() 的线程里,无法创建 handler

原因是修改 UI 需要在主线程里。

1. Thread

因为线程需要 Looper 来循环处理消息,但是子线程中默认是没有 Looper 的,查看一下 Looper 的源码,类注释如下:

/**
  * Class used to run a message loop for a thread.  Threads by default do
  * not have a message loop associated with them; to create one, call
  * {@link #prepare} in the thread that is to run the loop, and then
  * {@link #loop} to have it process messages until the loop is stopped.
  *
  * <p>Most interaction with a message loop is through 
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值