Search code examples
javaandroidandroid-activitytimer

How to delay a timer on an activity launch?


I have implemented a simple timer with CountDownTimer on my game and I need it to start ater a few seconds when the activity is started.

On my main activity's onCreate method, I call this:

playingTime();

Which is as follow

public void playingTime() {
    new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {
            String elapsedTime = String.valueOf(millisUntilFinished / 1000);
            timer.setText(elapsedTime);
        }

        public void onFinish() {

            timer.setText(R.string.timer_game_over_text);

        }
    }.start();

}

The timer start normally but immediatelly as the activity is launched. I would like to set a delay before it get executed or if there is a better way to set timer in games. (Count down timer and nomal timer)


Solution

  • You can add delay using Handler like as below:

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Executed after YOUR_DELAY_IN_MILLIS
        playingTime()
      }
    }, YOUR_DELAY_IN_MILLIS);
    

    Put the code in your activity onCreate() method