Stopping multiple countdown timers in Android

时间:2015-09-01 21:33:06

标签: android timer countdown countdowntimer

I need to find a way to stop multiple timers from happening. I have to have a popup menu with selectable countdown timer intervals. I found a solution that works for creating the timers. However, if one is going, and you select another from the menu, they will both run together.

I need to figure out what code to add so that when a second countdown option is selected, the first countdown timer stops.

...

@Override
public boolean onMenuItemClick(MenuItem item) {

    switch (item.getItemId()){
        case R.id.countdownMenu1:
            CounterClass timer = new CounterClass(10000, 1000);
            timer.start();
            return true;

        case R.id.countdownMenu2:
            timer = new CounterClass(15000, 1000);
            timer.start();
            return true;

        default:
            return false;
    }
}


public class CounterClass extends CountDownTimer  {

    public CounterClass(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onTick(long millisUntilFinished) {

        long millis = millisUntilFinished;
        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
        System.out.println(hms);
        textViewTime.setText(hms);
    }

    @Override
    public void onFinish() {
        // textViewTime.setText("Completed.");
        System.exit(0);
    }
...

Selecting each time from the menu works great, as long as you don't try to second another time. Then I get two countdown times being displayed and which ever gets to zero first executes the onFinish.

1 个答案:

答案 0 :(得分:0)

private CounterClass timer;

@Override
public boolean onMenuItemClick(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.countdownMenu1:
            startTimer(10000, 1000);
            return true;
        case R.id.countdownMenu2:
            startTimer(15000, 1000);
            return true;
        default:
            return false;
    }
}

public void startTimer(long millisInFuture, long countDownInterval) {
    cancelTimer();
    timer = new CounterClass(millisInFuture, countDownInterval);
    timer.start();
}

private void cancelTimer() {
    if (timer != null) {
        timer.cancel();
    }
}