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

之前开发中遇到这个问题:

java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()

这个错误看字面意思也能理解,就是无法再没有looper的线程中创建handler
通常出现在我们在子线程中嵌套一个子线程的情况。因为子线程是相对于主线程而言的,不能生成子线程的子线程。

解决方案有两种:
1.在我们新建非法子线程的地方做修改:

//在UI线程中做线程的新建操作
if (getActivity() != null) {
    getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//新线程中的操作
}
});
}

2.还是在我们新建非法子线程的地方做修改:

//传入一个mainLooper
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
//子线程中的操作
}
});
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值