关于子线程使用Toast报错Can't create handler inside thread that has not called Looper.prepare()的解决办法
形同如下代码,在Thread中调用Toast显示错误信息:
new Thread(new Runnable(){
@Override
public void run() {
try{
weatherData = getWeatherData(strUrl);
parseJson(weatherData);
}catch(Exception e){
Toast.makeText(WindowApplication.getAppContext(), e.toString(), Toast.LENGTH_SHORT).show();
Log.i("wytings",e.toString());
}
}
}).start();
一运行,就会报错Can't create handler inside thread that has not called Looper.prepare(),因为Toast的初始化函数中,自己开了个线程new Handler();所以使得当前的Toast要是不在主线程就会报错。
解决办法如下,在Toast上下添加Looper.prepare();和Looper.loop();
Looper.prepare();
Toast.makeText(WindowApplication.getAppContext(), e.toString(), Toast.LENGTH_SHORT).show();
Looper.loop();