如何在 Android Studio 1.0.2 中制作计时器?
How to make a timer in Android Studio 1.0.2?
我有这段代码,但我的应用程序在启动时崩溃了。此代码来自 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);
您在另一个 thread
中。您只能从 UIThread
修改您的 UI。你应该使用:
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);
这里是一段代码,timerLoopScan和scanPeriod是全局变量:
timerLoopScan = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
loopScan(); // your processings here
});
}
};
timerLoopScan.scheduleAtFixedRate(timerTask, 0, scanPeriod);
我有这段代码,但我的应用程序在启动时崩溃了。此代码来自 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);
您在另一个 thread
中。您只能从 UIThread
修改您的 UI。你应该使用:
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);
这里是一段代码,timerLoopScan和scanPeriod是全局变量:
timerLoopScan = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
loopScan(); // your processings here
});
}
};
timerLoopScan.scheduleAtFixedRate(timerTask, 0, scanPeriod);