How to set up a timer for an android game ? - android

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 ?

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?

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

Related

Android remove runnable callbacks

I am designing a bonus runnable such that for each question, if the user can complete the question earlier, there is a bonus score for time remaining for each question.
Code:
private Runnable Run_bonus_countdownHandler = new Runnable()
{
#Override
public void run()
{
if (game_pause ==false)
{
bonus_time_remaining = Math.max((bonus_time_remaining - 10),0);
bonus_countdownHandler.postDelayed(this, 10);
tv_bonus.setText("" + bonus_time_remaining);
if (bonus_time_remaining == 0)
{
tv_bonus.setText("0");
bonus_countdownHandler.removeCallbacks(this);
}
}
else
{
}
}
};
Question:
If the user expires the bonus time period, ie the countdown reach 0, when the user starts another question, the bonus countdown can be run smoothly and at the end be removed. However, if the user can finish earlier for the question, for the next question the countdown would skip some numbers and quickly down to 0.
I would like to ask how could code be modified such that the runnable be properly removed before starting a new question?
Thanks a lot!
I enjoyed your question, and tried to answer and build on it... So I wrote some code to manage these timers in a separate thread, with a simple callback mechanism for notifications.
There is a QuestionTimer class with a simple interface that handles the timed questions in a thread-safe manner, and an activity (MainActivity) to demonstrate how to use it. The QuestionTimer provides its listener with the remaining time through a callback, so you can easily add this as a bonus or add more time to the next question.
You can find the code here: https://gist.github.com/anonymous/182c13a4961515781be6
Hope this helps!

Android Eclipse - If button isn't pressed within 'x' seconds then

Trying to figure out how to do this, basically my App requires a button to be hit and hit multiple times, it counts how many times you hit it and if you don't hit one within a certain space of time it will display a message.
I just can't figure out how to get the 'If button isn't pressed within 'x' seconds then...' part, I've tried if(imagebutton1.isPressed()) statement but it checks it instantly when the actvity starts, I just want it to check 'X' amount of seconds after the button was last pressed.
ANy help is appreciated thanks.
In your case you would need to record the last time the button was pressed
Then add a updated while statement
In c++
Int presses;
Int timelimit; //the seconds between each press (you can use a chronometer but this is simpler but less accurate (and no decimals)
Int lastpressed; //need chronometer for more accuracy or decimals)
Int ammountpassed; //time since you pressed it
If(imagebutton1.isPressed())
{
Bool Started = Yes;
Presses++;
While(!imagebutton1.isPressed()&&ammountpassed<TimeLimit)
{
Ammountpassed++;
};
};
If (ammountpassed>=timelimit)
{
If (presses>=highscore)
{
DisplayMsg " Number of presses" presses; "! New highscore!";
};
Else(presses<highscore)
{
DisplayMsg "not fast enough! Number of presses" presses; "!" };
};
};
You will have to tweak it a bit to fit your needs ("displaymsg" I for think is the actual function so you might have to change that but there's the logic :)
I recommend hand typing this as I belive I may have made a few error but nothing adding a semi colon or 2 won't fix ;)
Hope it helps :) Good Luck :)
Every time the user hits the button you can post a message on the handler's queue with your text message to be displayed and the appropriate delay time (and remove previous messages). Therefore if the delayed time exceeds without any press the thread will execute the handler's message. Lets say you want to post to the main handler a message to be executed in delay number of milliseconds, then in your activity you would need to hold the reference to the handler and create a Runnable where the necessary text message will be displayed:
Handler mainHandler = new Handler(getMainLooper());
Runnable runnable = new Runnable(...);
In your OnClickListener of the button you would need to execute only:
#Override
public void onClick(View v) {
mainHandler.removeCallbacksAndMessages(null);
mainHandler.postDelayed(runnable, delay);
}

Handler to show the countdown timer is not reliable

I am developing an App where I show the countdown timer. To countdown the time I am using Handler class. Once the countdown timer reaches certain time the Alarm goes off. My problem is as below,
Initially I show the timer time as 04:00:00. Once it reaches 00:00:00 then the Alarm goes off. The Alarm code is working fine. But the timer display is not reliable. It works fine until I keep the App open. If I close the App (using Home or Back) or lock the device and open App again then the timer shown is not the correct one (delaying a lot, but still alarm works on-time). (But it works sometimes very fine under the same scenario). But whenever I ping the device to the system for checking the Log in eclipse that time all works fine!!!!!!!
1. I want to know whether I am using the Handler properly or not
2. (or) Is going out of the App or locking the device causing the problem
Below is my Handler code,
Handler digiHandler;
// Method to initialize the time and define the Handler
public void initialize(int hourstime,int mintime,int sectime){
hour = hourstime;
min = mintime;
sec = sectime;
digiHandler = new Handler();
handleRunnable = new Runnable(){
public void run(){
updateTimes();
}
};
}
public void startUpdateTheread(){
digiHandler.postDelayed(handleRunnable, UPDATEDELAY);
}
// Method to update the timer times
private void updateTimes(){
timerText = String.format(timerFormat,hour,min,sec );
-------------------------
-------------------------
-- code for incrementing the time ---
--------------------------
--------------------------
--------------------------
startUpdateTheread();
}
Please give the suggestions
Thanks
Edit:
When I observed the log it shows that to countdown 1 second of timer sometimes it is taking 1 minute time. The log is as below,
09-21 21:09:18.965: DEBUG/DigitalTimer(7656): timerText**:04:22:54
****long difference here****
09-21 21:10:19.308: DEBUG/DigitalTimer(7656): timerText**:04:22:53
..................................................................................
..................................................................................
..................................................................................
09-21 21:10:23.314: DEBUG/DigitalTimer(7656): timerText**: 04:22:49
**--long difference here ---**
09-21 21:11:22.604: DEBUG/DigitalTimer(7656): timerText**:04:22:48
It is happening always. So I can rule out that locking/coming out of an App is causing the problem. Seems I need to tweak the Handler part of the code.
The problem is that if the activity dies, then so does the thread it spawned, I recommend creating a service to handle this since such timers can be long i imagine (over 4 minutes) and in that time, you need the application to not die.
take a look at http://developer.android.com/reference/android/app/Service.html and let me know if that seems like a good enough solution.

Android - perform repititve task in service

I'd like to add a repititive taksk to a Service in my Android app. I've read about Runnable/Handler constructs, and about the Timer.scheduleAtFixedRate(). I'm wondering which one is the best approach.
I'm especially worried about the "scheduleAtFixedRate()" being run multiple times at once if execution takes longer than the interval. Or is that not possible?
How long is the interval? For this purpose, i think is good to use android AlarmManager.
It is for scheduling events on android, you can see a nice example here. And you can choose the method setRepeating instead set for repetive events.
static final long DELAY = 4000;
TimerTask task= new TimerTask (){
public void run(){
//do what you needs.
timer.shedule(this, DELAY);
}
}
Timer timer = new Timer();
timer.shedule(task, 0);
You can try this.

How do I use Android's CountDownTimer?

How do I use the Android's CountDownTimer?
I basically want to have the following scenario:
boolean 3_s_passed = false;
// setup counter to change 3_s_passed=true when it finishes
counter.start();
while(true){
if(3_s_passed || user_is_Done) break;
// do some stuff which may set user_is_Done to true
}
So either 3 seconds passed or the user finishes and I'm out of the loop.
Will the while-loop code run before the counter finishes? Is my understanding of the CountDownTimer correct?
Thanks for your help
You could use a handler for this. Make a Runnable with the task to complete after 3 seconds or when the user does the task. Post it for 3 seconds and remove callbacks if the user does whatever. The code same below shows how to properly use the Handler but isn't looping to allow the user to make the action you'll have to figure that out on your own :)
Runnable action = new Runnable(){
public void run(){
//...
}
};
mHandler.postDelayed(action, 3000);
if(userDone){
mHandler.removeCallbacks(action);
mHandler.post(action);
}
Don't use this class it contains a race in cancel method.
https://code.google.com/p/android/issues/detail?id=58668
cancel don't work in case of race between onTick and cancel.
It's better to implement it from scratch without races.
In other case you will have a problem until official fix.

Categories

Resources