Question

I want to programm a game for Android.

Play principle: The user should have a short time to choose the correct answer.

My problem is the combination between the input (choosing the answer) and the time (countdown). I tried to run a thread, but the thread isn't stoppable. So the user gives the answer, the next activity will be shown and after a while (when the "timer" becomes 0) the activity will be shown again.

  • How could I implement this in a correct way?
  • Should I use Thread, Handler, CountDownTimer ?
Was it helpful?

Solution

You can keep a running timer using this on init:

Timer updateTimer = new Timer("update");
updateTimer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
    updateGUI();
        }
    }, 0, 1000);
long startTime = System.currentTimeMillis();

Then in a Thread:

//Clock update
currentTime = System.currentTimeMillis() - startTime;
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
clock.setText(sdf.format(currentTime));
clock.invalidate();

You could stop the Thread with a boolean inside or outside as you please?

OTHER TIPS

Okay, I don't know the specific libraries to use, and I haven't done any thread programming myself, but I would think of the program as a state machine. I hope it helps :/

Set up a boolean userHasAnswered = false.

Set up a specialized listener (e.g. touch listener for some button) for answers. If the listener gets an appropriate response from the user, set userHasAnswered = true.

When question loads up, start the thread which counts down.

If user fails to give ans when the time reaches zero, just call loadNextQuestion().

In your thread, do periodic checks every few units of time to see if userHasAnswered == true, and if it is true, then call updateScore() and loadNextQuestion().

You may want to have a look at alarm manager

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top