android Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread that has not called
仔细检查了代码,不应该异常啊?? 没有 handler相关代码啊?
原来是在子线程弹Toast了, 切记,Toast只能在UI线程弹出,如果一定要在子线程弹,那么就通过 new Handler(Looper.getMainLooper()) 来弹
private void toastTest() {
new Thread(new Runnable() {
@Override
public void run() {
<span style="color:#cc0000;">Handler handler = new Handler(Looper.getMainLooper());</span>
handler.post(new Runnable() {
@Override
public void run() {
//放在UI线程弹Toast
Toast.makeText(MainActivity.this, "toast in work thread", Toast.LENGTH_LONG).show();
}
});
//此处会发生异常
// Toast.makeText(MainActivity.this, "toast in work thread", Toast.LENGTH_LONG).show();
}
}).start();
}