I would do something like this:
private void startNewTimer(List<CountDownTimer> listOfTimers) {
CountDownTimer countDownTimer = new CountDownTimer(1000,1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
}
}.start();
listOfTimers.add(countDownTimer);
}
private boolean cancelTimers(List<CountDownTimer> listOfTimers) {
if(listOfTimers != null && !listOfTimers.isEmpty()) {
for(CountDownTimer cdt : listOfTimers) {
cdt.cancel();
}
listOfTimers = null;
return true;
}
return false;
}
You may want to create your List<CountDownTimer> listOfTimers
as a global variable (List<CountDownTimer> listOfTimers = new ArrayList<>()
)
You would call the the startNewTimer(list)
from the onClick
method of your button OnClickListener
and the stopTimers
where you see fit.
If you want to cancel a specific cancel you could reference it through its index in the List
likes this:
private boolean stopTimer(List<CountDownTimer> listOfTimers, int index) {
if(listOfTimers != null && listOfTimers.size() > index) {
for(int i = 0; i < listOfTimers.size(); i++) {
listOfTimers.get(i).cancel();
}
return true;
}
return false;
}
solved How to control multiple CoundownTimer in android