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

来源:互联网 发布:矩阵的秩代表什么 编辑:程序博客网 时间:2024/06/05 19:39

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

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() {@Overridepublic void run() {//新线程中的操作}});}

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

//传入一个mainLooperHandler handler = new Handler(Looper.getMainLooper());handler.post(new Runnable() {@Overridepublic void run() {//子线程中的操作}});
0 0
原创粉丝点击