我有这个代码,我的应用程序在启动时崩溃了。此代码来自onCreate方法。
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TextView txtClicks = (TextView) findViewById(R.id.txtClicks);
// task to be done every 1000 milliseconds
iClicks = iClicks + 1;
txtClicks.setText(String.valueOf(iClicks));
}
}, 0, 1000);
答案 0 :(得分:3)
你在另一个thread
内。您只能从UIThread
修改您的用户界面。你应该使用:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable(){
@Override
public void run(){
TextView txtClicks = (TextView) findViewById(R.id.txtClicks);
// task to be done every 1000 milliseconds
iClicks = iClicks + 1;
txtClicks.setText(String.valueOf(iClicks));
}
});
}
}, 0, 1000);
答案 1 :(得分:0)
这是一段代码,timerLoopScan和scanPeriod是全局变量:
timerLoopScan = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
loopScan(); // your processings here
});
}
};
timerLoopScan.scheduleAtFixedRate(timerTask, 0, scanPeriod);