-1

In my game I give 5 seconds to answer each question. If a user selects the correct answer then I show him/her the next question. If a user can't answer the question, the level is set to the first question (each question is a level).

How can I put a timer in my code?

enigma
  • 3,476
  • 2
  • 17
  • 30
Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47

2 Answers2

0
Timer timer;
TimerTask timertask;
timer = new Timer();
timertask = new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // add your code here that will run after 5 seconds.        
            }
        });
    }
};
timer.schedule(timertask, 5000);

Use timer task for scheduling the execution. For more info Check Here Timer Task and Timer

Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
0

From Android developper :

CountDownTimer myCountDown = new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }
}.start();

You can use these callbacks to handle ticks and the end of timer.

The first paramter determinates the duration of the timer.

The second parameter of CountDownTimer determinates the duration of one tick until the end.

EDIT:

If you need to stop the timer before the end of your 5 seconds, you can store the current time before launch your countdown:

final long timeBeforeLaunchCountDown = System.currentTimeMillis();

So, when a click occurs (user answers to your question), you can just compare the new current time with your previous time and stop the countDown:

if((System.currentTimeMillis() - timeBeforeLaunchCountDown) > 5000){
    myCountDown.cancel();
}
  • how to get CountDownTimer value for compare with System.currentTimeMillis() ? – Farshid Shekari Sep 29 '15 at 16:14
  • I don't know if it's possible directly but you can store the current time when you launch your timer then you can compare when a click occurs the new current time if less than the referenced current time + 5 seconds – Jean-baptiste Valero Sep 29 '15 at 16:29
  • Why do you want to `compare`? The CountDownTimer does it for you! Once started, just forget about it. – Phantômaxx Sep 30 '15 at 06:53
  • Because maybe sometimes, you want stop the timer before is finish and before it does his onFinish method, it could be useful to compare with the time. If you wait always the end of timer to get the answer, ok. Don't compare. – Jean-baptiste Valero Sep 30 '15 at 07:16