[英]How to execute a function every two seconds in Java on Android?
I'm trying to execute a chunk of Java code in my Android program every two seconds. 我试图每两秒在我的Android程序中执行一大块Java代码。 My code currently looks like this: 我的代码目前看起来像这样:
LinearLayout.postDelayed(new Runnable() {
public void run() {
//Do stuff here
}
}, 2000);
Unfortunately, this only runs once after two seconds and then never runs again. 不幸的是,这只在两秒后运行一次然后再也不会运行。 How could I get it to run every two seconds? 我怎么能让它每两秒运行一次?
Thanks in advance for all your help. 在此先感谢您的帮助。
Try this: 尝试这个:
LinearLayout.postDelayed(new Runnable() {
public void run() {
//Do stuff here
// assuming LinearLayout is enclosing class
LinearLayout.this.postDelayed(this, 2000);
}
}, 2000);
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Enter your code which you want to execute every 2 second
}
}, 0, 2000);//put here time 1000 milliseconds = 1 second
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.