创建子线程http请求查询的时候闪退,查了一下报错:Can’t create handler inside thread that has not called Looper.prepare()。是因为我用Toast提示网络请求超时导致的。
解决办法:
在子线程run方法里面加上Looper.prepare();和Looper.loop();代码包住要执行的代码,如:
private void getLabelRule(){
//启动一条子线程去查询,因为安卓4.0以后http请求不允许在主线程进行
new Thread(new Runnable() {
@Override
public void run() {
//加Looper解决http访问超时的时候,Toast提示闪退
Looper.prepare();
HttpRequest.getLableRule(mContext);
Looper.loop();
}
}).start();
}
原因:非主线程中没有开启Looper,而Handler对象必须绑定Looper对象需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用。