我正在使用此代码:
public class newtimer extends Activity {
private Timer myTimer;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
int number = 0;
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show();
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
Toast.makeText(getBaseContext(), "UI Thread Running "+number, Toast.LENGTH_SHORT).show();
}
};
}
当我运行它时,我在logcat中得到了这个异常:
09-06 21:39:39.701:ERROR / AndroidRuntime(1433):java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
答案 0 :(得分:0)
我认为问题在于TimerMethod函数中的Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show();
- 您无法从工作线程调用与UI相关的任何函数。既然你已经在UI线程中运行的部分中有Toast,为什么在TimerMethod中有另一个Toast?
对于调试,我建议尽可能使用Log而不是Toast。