1

I have one CountDownTimer and i want to do an action for every two wasted seconds.

countdowntimer = new CountDownTimer(10000, 1) {

            @Override
            public void onTick(long millisUntilFinished) {


            }

            @Override
            public void onFinish() {




            }
        }.start();

For example when it starts time remaining = 10 seconds

When time remaining = 8 seconds I want to do an action

When time remaining = 6 seconds I want to do an action

and so on......

noobProgrammer
  • 1,443
  • 4
  • 14
  • 33

1 Answers1

3

Just check if it is divisible by 2.

@Override
public void onTick(long millisUntilFinished) {
      long seconds = millisUntilFinished/1000;
      if ((seconds % 2) == 0)
      {     // even number--do some action  }
}

This is assuming you are calling the onTick() every second like

countdowntimer = new CountDownTimer(10000, 1000) {

This is probably preferable for you

Setting it up to call every 2 seconds should also work and better but leaving the original answer in case someone needs to call onTick() more often

countdowntimer = new CountDownTimer(10000, 2000) {

then you could just do the action with every call to onTick()

CountDownTimer Docs

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • 2
    @noobProgrammer how do you know he downvoted? It was downvoted a long time back even before codeMagic answered. There is no way you can know who downvoted – Raghunandan Mar 16 '14 at 17:27
  • @ataulm you are absolutely correct. However, the `onTick()` will be called at certain intervals depending on how the constructor is set up. I am assuming it is being called every second. – codeMagic Mar 16 '14 at 17:35
  • that's for every 2 seconds? – noobProgrammer Mar 16 '14 at 17:38
  • See my updated answer. I didn't notice your constructor when I answered. The constructor takes a `long` for millis...not seconds. You are calling it right now every millisecond which probably isn't what you want. – codeMagic Mar 16 '14 at 17:40
  • 1
    @codeMagic I prefer the edited answer (+1); 1000ms is still divisible by 2 so the first answer wouldn't work - perhaps edit it to remove that portion (if you agree with my reasoning). – ataulm Mar 16 '14 at 17:40
  • 1
    @ataulm I prefer the edited answer also ;) I got a little hasty and the original answer would take more checks. – codeMagic Mar 16 '14 at 17:41
  • 1
    @ataulm I have edited to make it correct. I think I'm done screwing up for now :P Thanks for catching that – codeMagic Mar 16 '14 at 17:44