0

I'm creating a game where the user will have X seconds to make his move every turn, so I need to show the amount of seconds remaining and control the game.

If the user makes his move before countdown is complete, the countdown is cancelled and started again as a new turn. And if the countdown ends before the user makes his move, the game is ended.

Important: each second (timer tick event) a sound is played and this shouldn't affect the timer interval.

How can I do this? Should I use a Timer, a CountDownTimer or something else?

juliano.net
  • 7,982
  • 13
  • 70
  • 164

2 Answers2

1

You have to use CountDown Timer as your requirement........

here you can control timer calling Below code...

if (!timerHasStarted) { 
           countDownTimer.start(); 
           timerHasStarted = true; 
           startB.setText("STOP"); 
          } else { 
           countDownTimer.cancel(); 
           timerHasStarted = false; 
           startB.setText("RESTART"); 
          }

follow below link..

http://androidbite.blogspot.in/2012/11/android-count-down-timer-example.html

Devganiya Hitesh
  • 1,207
  • 2
  • 17
  • 31
0

You may use CountDownTimer:

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
        //Play your audio here
     }

     public void onFinish() {
         //Trigger the game end action
     }
  }.start();

call cancel() to stop the timer.

Reference: CountDownTimer

hungr
  • 2,086
  • 1
  • 20
  • 33
  • If you run this code you may notice that the first tick event seems to have run in less than 1 second. – juliano.net May 20 '14 at 09:47
  • @Juliano Nunes Silva Oliveira: CountDownTimer is not precise. Please refer to these: http://stackoverflow.com/questions/6810416/android-countdowntimer-shows-1-for-two-seconds and http://stackoverflow.com/questions/4824068/how-come-millisuntilfinished-cannot-detect-exact-countdowntimer-intervals – hungr May 20 '14 at 10:02
  • I'm affraid that decreasing the interval to just 100ms would cause some kind of overhead. I'll make some tests. – juliano.net May 20 '14 at 11:38