I'm trying to execute a chunk of Java code in my Android program every two seconds. 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
Put your code in a loop. Or you could look into Alarms .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.