java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因1:
子线程直接更新ui
8月9日在service中创建子线程时再次遇到
java.lang.RuntimeException: Can't create handler inside thread Thread that has not called Looper.prepare()
这个问题。代码如下
new Thread(new Runnable() {
@Override
public void run() {
timer = new Timer(mTotalTime, TimeSetted.SECOND_TO_MILL);
timer.start();
Log.d(TAG,"Countdown start");
}
}).start();
修改为
new Thread(new Runnable() {
@Override
public void run() {
Looper.perpare();//增加部分
timer = new Timer(mTotalTime, TimeSetted.SECOND_TO_MILL);
timer.start();
Log.d(TAG,"Countdown start");
Looper.loop();//增加部分
}
}).start();
后,应用正常运行。即在具体逻辑的前后加入Looper.perpare()和Looper.loop()方法。
查了一下报错原因:非主线程中没有开启Looper,而Handler对象必须绑定Looper对象需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用。
问题来了,
在这个子线程和之前的doInBackground中,都没有new一个handler,为什么会出现这个错误?
查看了一下代码中使用的CountdownTimer的源码,start(),pause(),cancel()方法都是用message和handler实现的,在子线程中使用CountdownTimer时,由于没有默认绑定Looper,因此会报错。
结论:
1.Can't create handler inside thread Thread that has not called Looper.prepare()通常是在子线程中使用没有绑定Looper的handler时出现,只需在handler语句的前后加Looper.prepare()和Looper.loop()方法即可。
2.创建子线程和使用AsyncTask的doInBackground时,若没有new一个handler对象,通常不会出现这个错误。本人是由于在调用其他方法时用了handler导致报错。