参考:
Can’t create handler inside thread that has not called Looper.prepare()
Android 如何判断当前线程是否是主线程
子线程中直接toast报错:
Can't create handler inside thread that has not called Looper.prepare()
原因:
UI的显示要在UI线程中执行,而不能在子线程中,也不能在异步线程中执行
常见于toast的显示。
解决方法:
if (!NetUtils.isNetworkAvailable(WeatherApplication.getContext())) {
if (Looper.getMainLooper() == Looper.myLooper()) {//主线程
Toast toast = Toast.makeText(WeatherApplication.getContext(),
"网络异常,请查看网络设置", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {//子线程
Looper.prepare();
Toast toast = Toast.makeText(WeatherApplication.getContext(),
"网络异常,请查看网络设置", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Looper.loop();
}
return "";
}