For my project, I am trying to execute a Method every 10 seconds when I click a button "A" and it should stop when I click the button again (kind of on/off).
this is what i reached :-/ :
ButtonA.setOnClickListener(new OnClickListene开发者_如何学Gor() {
@Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
showCurrentLocation();
Methodexecute();
}
}, 10000);
}
}
});
How can I repeat executing this method every 10 seconds until the button is clicked again?
thanks
Consider using a Timer with a TimerTask, scheduling it every 10 seconds. I hope this will work:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
//insert your methods here
}
};
boolean taskIsRunning = false;
if(taskIsRunning){
timer.cancel();
taskIsRunning = false;
} else {
timer.schedule(task, 0, 10000);
taskIsRunning = true;
}
handler = new Handler();
ButtonA.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
handler.postDelayed(new Runnable() {
public void run() {
if(taskIsRunning){
showCurrentLocation();
Methodexecute();
handler.postDelayed(this,10000);
}
}
}, 10000);
}
}
});
In your onClick method you can also toggle the timer task like so:
...
@Override public void onClick(View v) {
...
toggleTask();
...
}
...
and then, from Jonathan's code, something like
boolean taskIsRunning = false;
Timer timer;
TimerTask task = new TimerTask() {
@Override
public void run() {
//insert your methods here
}
};
private void toggleTask() {
if(taskIsRunning){
timer.cancel();
taskIsRunning = false;
} else {
timer = new Timer()
timer.schedule(task, 0, 10000);
taskIsRunning = true;
}
}
精彩评论