android Toast提示異常:java.lang.RuntimeException: Can't create handler inside thread that has not called
阿新 • • 發佈:2019-01-08
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(); }