我想在计时器中显示toast消息,我使用了以下代码:
timer.scheduleAtFixedRate( new TimerTask() { public void run() { try { fun1(); } catch (Exception e) {e.printStackTrace(); } } },60000); public void fun1() { //want to display toast }
我收到以下错误:
WARN/System.err(593): java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
WARN/System.err(593): at android.os.Handler.(Handler.java:121)
WARN/System.err(593): at android.widget.Toast.(Toast.java:68)
WARN/System.err(593): at android.widget.Toast.makeText(Toast.java:231)
谢谢.
解决方法
您不能在单独的Thread内部进行UI更新,例如Timer.您应该使用Handler对象进行UI更新:
timer.scheduleAtFixedRate( new TimerTask() { private Handler updateUI = new Handler(){ @Override public void dispatchMessage(Message msg) { super.dispatchMessage(msg); fun1(); } }; public void run() { try { updateUI.sendEmptyMessage(0); } catch (Exception e) {e.printStackTrace(); } } },60000);