Extend time of an Countdowntimer - java

Why is this Code not working ?
This code should extend the Countdowntimer to 10 sec (everytime when point is 20 , 40 , 60) etc.But when I start it and my score is by 20 it shows in a TextView a right value of time.But then it is gone in 1 sec and the Countdowntimer got the old value and continue.Someone a idea ?
int bonus_time = 1 , sec = 10000 , point == 0;
points_timer =new CountDownTimer(sec,1000) {
#Override
public void onTick(long millisUntilFinished)
{
if ( point == (bonus_time * 20))
{
++bonus_time;
millisUntilFinished += 10000;
sec += 10000;
}
++point;
}
#Override
public void onFinish()
{
bonus_time = 1;
}
};

When you create a timer with the sec variable for its time, it does not magically connect the two so when the value of sec changes the timer's time changes, it just uses the value of sec once when you make the timer.
Same goes for changing millisUntilFinished, it's a parameter you got from a callback, by changing its value you are not doing anything.
The only way to change a timer's time is to create a new one. This is my suggestion:
// GLOBAL VARIABLES
CountDownTimer points_timer;
int bonus_time = 1 , sec = 10000 , point == 0;
public void createTimer()
{
points_timer =new CountDownTimer(sec,1000) {
#Override
public void onTick(long millisUntilFinished)
{
sec = millisUntilFinished;
if ( point == (bonus_time * 20))
{
++bonus_time;
//millisUntilFinished += 10000;
sec += 10000;
createTimer();
}
++point;
}
#Override
public void onFinish()
{
bonus_time = 1;
}
};
}
The creation of the timer is surrounded by a function, and that function is called each time the bonus is gained to recreate the timer with the new value of sec.
You should also call that method once in place of your previous code, to initially create the timer.
Hope this works..

There is no way to extend a CountDownTimer, no method in the class provides this.
Your attempt to add time to sec is useless, I even wonder how it can compile. Anyway, in Java integers are passed by value, so once you passed 1000, you passed it and can't change that value.
The only alernative is to re-create a new timer and use it instead of the old one. Or recode everything, a timer of your own that you can extend.

in
public void onTick(long millisUntilFinished)
you do
millisUntilFinished += 10000;
you can not assign to primitive parameter and expect that it changes anything outside of that method (eg. scope of millisUntilFinished is onTick method and nothing more)

Related

How can I stop a Swing Timer after n seconds?

I'm trying to make an image twinkle with RaffleImage(); while I'm executing the timer, my character is immune to any collision, I want it to be immune only for 2 seconds, so the timer get execute only for 2 seconds and then get finished.
I've tried subtracting System.currentTimeMillis() but any variable I create from this method, have always the same value, making me get a zero from that subtracting.
Do you know how I can stop or pause the timer after any elapsed time in seconds?
immuneTimer = new Timer(50, new ActionListener() {
#Override
public synchronized void actionPerformed(ActionEvent e) {
long initMillis = System.currentTimeMillis();
if (System.currentTimeMillis() - initMillis > 2000 ) { // this substract gives me 0
initImages();
setImmune(false); // so this never reached
immuneTimer.stop();
} else {
raffleImage(); //its executing like forever;
}
}
});
The Swing timer fires a an ActionEvent. From the event you can use getSource() to get the source of the event. Cast that source to the swing timer object and use that to turn it off.
To know when to turn it off you need to have a variable count the number of times the swing timer is invoked. When the variable reaches that amount, turn it off.
int elapsedTime = 0;
int timerDelay = 50;
int max = 2000;
public void actionPerformed(ActionEvent ae) {
elapsedTime += timerDelay; // you could use getDelay here but it
// is in milliseconds.
if (elapsedTime >= max) {
Timer s = (Timer)ae.getSource();
s.stop();
}
// rest of code
}

Double (chess like) timer

I am thinking about making an android app to support a game of mine, and I can't find info on how to do it. Here is an app explanation:
The app should have two timers (both set for x minutes). When first player starts his turn (by a button click) his time starts running out. when first player makes his move, he should click his time to stop it, and player two starts his turn.
NOW, the problem I can't find a solution for - When player one takes his turn, time that he loses should pass to the other player's timer.
Example: Both players start with a 5 minute timer. If player one takes 30 second for his turn, his time should go down to 04:30, at which time he clicked on his timer. During that time, for each second he lost, the other player gained time on his timer, so at the beginning of his turn, his time is 05:30. The time goes back and forth, and the player whose timer runs out loses the game.
Any idea how to do this?
I am still stuck to the idea on how to make it, so I have no code to share.
Thank you all for your answers, and effort in helping me, if you have a question I haven't covered, I will gladly answer it.
First, you will need to instantiate class of CountDownTimer everytime you click on button.
For reference check here: https://developer.android.com/reference/android/os/CountDownTimer.html
You have two parameters long millisInFuture, long countDownInterval
Before you start, you will need to create two global variables one for first player, and one for second player like this:
long firstPlayerRemainingTime = 5 * 60 * 1000; // start time 5 minutes
long secondPlayerRemainingTime = 5 * 60 * 1000;
long limitedTime = 30 * 1000; // 30 seconds
CountDownTimer mCountDownTimer;
Now we have came to the most important part and that is logic inside onClickListener method
I don't know if there are two buttons or one, but I will go with two buttons:
btnFirstPlayer.setTag(1); // start timer
btnFirstPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnFirstPlayer.getTag() == 1) {
startTimer();
} else {
stopTimer();
}
});
private void startTimer() {
long startTime = firstPlayerRemainingTime;
btnFirstPlayer.setTag(2); // stop timer
btnFirstPlayer.setText("Stop");
mCountDownTimer = new CountDownTimer(firstPlayerRemainingTime, 1000) {
public void onTick(long millisUntilFinished) {
firstPlayerRemainingTime = millisUntilFinished;
tvPlayerOneTimer.setText("" + firstPlayerRemainingTime / 1000)
// Here you would like to check if 30 seconds has passed
if ((startTime / 1000) - (limitedTime / 1000)
== (firstPlayerRemainingTime / 1000)) {
stopTimer();
}
// Here you would like to increase the time of the second player
secondPlayerRemainingTime = ++1000;
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
}
}
private void stopTimer() {
btnFirstPlayer.setTag(1);
btnFirstPlayer.setText("Start");
mCountDownTimer.cancel();
// I guess here starts second player move
}
The same logic would go for second player. Let me know if this helped you or if I need to explain anything.

Java Timer.Schedule (infiniti loop) stop running

I have the follow problem:
i'm writing an chat bot in java and i want to call a method even x minutes.
So i read an "Timer.Schedule" is what i need. So i write the following method:
public function timerMethod()
{
int time = 10;
...
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 1000 * 60 * time // 1MSec * 1Sec * xMin
);
}
At the beginning the loop works fine but after a few hours (i think it's after 10-15 hours) the loop dont work anymore...
I dont know why i dont work and dont get any error message :(
Can someone help me pleace???
So you want code to run for x minutes, correct?
If so, convert the time you want the code to run for into milliseconds like this : 1 minute = 60000 ms. There is a method called System.currentTimeMillis(), this will return a value of miliseconds from the EPOCH date (Jan 1, 1970).
You can use a while loop like this:
`
int msTime = 60000; //1 Minute = 60000 MS
int doUntil = ms + System.currentTimeMillis(); //1 minute
while(System.currentTimeMillis() != doUntil)
{
//Code here
System.out.println(¨Hello World¨); //This will print Ḧello World for 60000ms
}
Mmm well first you can stop instantiating multiple times the java.util.Timer() variable. You only need one as an attribute of the class. The timerTask is the only one there that should be reinstantiated.
private Timer timer = new Timer();
Now, surround your code inside the run function with try/catch:
public void run() {
try {
timerMethod();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
Are you calling that timerMethod just once? You can add to this code some prints too in order to check whenever you reschedule your function and when you run your method.

How to make a countdown?

I'm trying to create a countdown. I don't see how exactly I can make a countdown. Can anyone help?
The code does what you tell it. You say in onStart:
end.add(Calendar.MINUTE, 4);
end.add(Calendar.SECOND, 5);
which tells the system you want a countdown starting at 4 minutes and 4 seconds. Instead, do:
end.add(Calendar.SECOND, 45);
EDIT
Took a while to understand what you meant. First, go to github and copy TickTockView into your own project. Remove the dependency to the original project. Open the file and in onDraw, change:
if (mCircleDuration == DURATION_TOTAL && mStartTime != null) {
long totalTime = mEndTime.getTimeInMillis() - mStartTime.getTimeInMillis();
float percentage = (((float) mTimeRemaining) / ((float) totalTime));
angle = 360f * percentage;
}
to:
if (mCircleDuration == DURATION_TOTAL && mStartTime != null) {
long totalTime = mEndTime.getTimeInMillis() - mStartTime.getTimeInMillis();
float percentage = (((float) mTimeRemaining) / ((float) 45000));//45000(ms) = 45 seconds
angle = 360f * percentage;
}
In your xml file where the circle is defined, add:
app:tickCircleDuration="total_time"
And by doing that, you only need to change totalTime in onDraw in the TickTockView. Remember to update the package name in the XML file to point to the place you saved the file, not the original project.
For reference, this is the file you should copy
The good way is to use CountDownTimer class provided by Android for downward counting in time. I have recently used it in my game and is simple in use. First you
CountDownTimer timer = new CountDownTimer(45000, 1000) {
// 45000 milliseconds countdown and 1000 milliseconds decrement at each tick.
public void onTick(long millisUntilFinished) {
//you can change your UI here based on time
}
public void onFinish() {
// you can define something to happen when timer ends.
}
};
timer.start();
Change the below code into
Calendar end = Calendar.getInstance();
end.add(Calendar.MINUTE, 4);
end.add(Calendar.SECOND, 5);
into
Calendar end = Calendar.getInstance();
end.add(Calendar.MINUTE, 0);//O minute
end.add(Calendar.SECOND, 45);//45 second

Problems with CountDownTimer and .setBackgroundColor() / .setTextColor()

I've looked everywhere for an answer but cannot find one for my situation. I have a couple problems and also wonder how to include millisecond countdown as well. I'm trying to get a countdown timer in the format 00.00 (seconds.milliseconds). A button is used to start the timer. The times I use depend on the button pressed, 5, 10, 15, 30, or 90 seconds. I'll just says its hard coded to 5000 ms to make simpler for now.
long timeSecs = 5000; // really timeSecs is dynamic but for the sake of simplicity
long countDownInterval = 1000; // this is a static value
TextView TVcountDown = (TextView)findViewById(R.id.TVcountDown);
public void createTimer() {
new CountDownTimer(timeSecs, countDownInterval) {
public void onTick(long millisUntilFinished) {
TVcountDown.setText(millisUntilFinished / 1000); // error here on
//.setText unless I cast to an int, which all values are long so I'm not sure why
}
#Override
public void onFinish() {
TVcountDown.setBackgroundColor(R.color.solid_red); // error here
TVcountDown.setTextColor(R.color.white); // error here
TVcountDown.setText("Expired"); // it will make it here
// It doesn't count down, just goes straight to onFinish() and displays "Expired"
}
}.start();
}
Thanks in advance. I've been beating my head against the desk for awhile now.
Try this.
For setText
TVcountDown.setText("" + (millisUntilFinished / 1000));
For the color
Resources res = getResources();
TVcountDown.setBackgroundColor(res.getcolor(R.color.solid_red));
TVcountDown.setTextColor(res.getcolor(R.color.white));
you should get color from the color resource before setting.

Categories