如何在Android上每两秒钟执行一次Java函数?
问题描述:
我试图每两秒在Android程序中执行一段Java代码。我的代码目前看起来是这样的:如何在Android上每两秒钟执行一次Java函数?
LinearLayout.postDelayed(new Runnable() {
public void run() {
//Do stuff here
}
}, 2000);
不幸的是,这个只有两秒钟后,运行一次,然后再也没有运行。我怎样才能让它每两秒钟运行一次?
在此先感谢您的帮助。
答
试试这个:
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
是什么'll'在你的代码? – 2011-05-05 18:44:09