java 如何在 Android Studio 1.0.2 中制作计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28243847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a timer in Android Studio 1.0.2?
提问by Saibamen
I have this code and my app is crashing at startup. This code is from onCreate method.
我有这个代码,我的应用程序在启动时崩溃了。此代码来自 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);
回答by vinitius
You're inside a different thread
. You can only modify your UI from the UIThread
. You should use:
你在一个不同的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);
回答by LeGeekDOzoZoo
Here is a piece of code, with timerLoopScan and scanPeriod being global variables :
这是一段代码, timerLoopScan 和 scanPeriod 是全局变量:
timerLoopScan = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
loopScan(); // your processings here
});
}
};
timerLoopScan.scheduleAtFixedRate(timerTask, 0, scanPeriod);