How to add time to countdown timer?

AtomicTim picture AtomicTim · Jun 29, 2013 · Viewed 10.3k times · Source

I know there is a post like this but it does not answer the question clearly. I have a little game where you tap a head and it moves to a random position and you get +1 to score. Meanwhile there is a timer counting down from 60000 (60 seconds) and displaying below. How can I make it so whenever the head is tapped, it adds a second to the timer?

new CountDownTimer(timer, 1) {
    public void onTick(long millisUntilFinished) {
        textTimer.setText("Timer " + millisUntilFinished/1000);
    }
    public void onFinish() {
        Intent intent = new Intent(MainActivity.this, Gameover.class);
        startActivity(intent);
    }
}.start();

and in the onClickListner event I have:

timer=timer+1000;

It currently doesn't work as in there is no time added on the click.

Any help would be appreciated :)

Answer

G_J picture G_J · Jun 29, 2013

You can't change the time of a scheduled timer. The only way to achieve what you are trying to do is by cancelling the timer and setting up a new one.

public class CountdownActivity extends Activity implements OnTouchListener{
    CountDownTimer mCountDownTimer;
    long countdownPeriod;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_countdown);
       countdownPeriod = 30000;
       createCountDownTimer();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mCountDownTimer != null)
                mCountDownTimer.cancel();
        createCountDownTimer();

        return true;
    }

    private void createCountDownTimer() {
        mCountDownTimer = new CountDownTimer(countdownPeriod + 1000, 1) {

            @Override
            public void onTick(long millisUntilFinished) {
                    textTimer.setText("Timer " + millisUntilFinished / 1000);
                countdownPeriod=millisUntilFinished;
            }

            @Override
            public void onFinish() {
                Intent intent = new Intent(MainActivity.this, Gameover.class);
                startActivity(intent);
            }
        };
    }
}