public void counter(){
new CountDownTimer(20000, 1000){
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(Integer.parseInt(String.valueOf(millisUntilFinished/1000)));
}
#Override
public void onFinish() {
gameOver();
}
}.start();
}
I am trying to write a game in which player gets 20 seconds to play. A timer starts at start of the game and if timer reaches 0, player looses. If player presses button with correct answer, i want time to increase by 3 seconds. But I don't know how to add time in the count down timer whenever player hits correct answer. I tried everything but couldn't find a way. If there is another method to achieve this, please tell me. Thank you
Change your code like this:
private int globalCount = 0; // Initialize this in Global scope of class.
public void counter(int timeCount){
globalCount = 0;
new CountDownTimer(timeCount, 1000){
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(Integer.parseInt(String.valueOf(millisUntilFinished/1000)));
}
#Override
public void onFinish() {
if (globalCount == 0) {
gameOver();
} else {
conter(globalCount);
}
}
}.start();
}
One last thing you have to do is:
globalCount += 3000;
every time when user pressed the right answer button. Hope this will help!
In Android normal countdown timer is used for decrease order. so you can use logic using normal if-else condition.
if (sec==59){
sec = 0;
min = min+1;
String text = String.format(Locale.getDefault(),"%02d min: %02d sec",min,sec);
editText.setText(text);
}else {
sec = sec+1;
String text = String.format(Locale.getDefault(),"%02d min: %02d sec",min,sec);
editText.setText(text);
}
}
You can get complete code using this blog
Related
I'm trying to make a class called timer. The timer class is supposed to be called upon when my character enters the enemy's area. And the timer class is supposed to remove the characters health by 10-health points every 5 seconds. Ive tried multiple different timers but i cant seem to get any of them right. When i tried it removed health but it didn't do it only once, it kept repeating it until the health bar was out of the screen. here is my code:
class Timer {
g = new gubbe();
gubbe g;
Timer timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
g.RemoveHealth();
}
});
timer.setRepeats(false);
timer.start();
}
That is what I've come up with so far.
If any more code is needed just ask.
Here's a class which you can use to time your events:
class Delay {
protected int limit;
public Delay() {limit = millis();}
public Delay (int l) {
limit = millis() + l;
}
public boolean expired () {
if (millis() > limit) { return true; }
return false;
}
}
To check on something every 5 seconds, you would have to initialize it like this:
Delay _delay;
void setup() {
_delay = new Delay(5000);
}
void draw() {
if (_delay.expired()) {
//do something
_delay = new Delay(5000);
}
}
The 5000 is in milliseconds, so it means 5 seconds. If you want to check for a 1 second delay, it would be 1000 instead. We re-initialize it when the delay is finished so it triggers again in 5 more seconds.
Have fun!
I've been trying to run a countdown timer in a for loop but whenever I do, instead of the countdown timer keeping its timing and carrying out some code in the onTick() method, all the code in the onTick() method gets carried out instantly without the delay. Any way to fix this, or an alternative approach to what i'm trying to achieve?
Here's my code :
public void runFromString(String theString, final TextView textView) {
for (final Lyric lyric : lyricArrayList(theString)) {
final int[] j = {0};
new CountDownTimer(lyric.timeInMillis(), 1000) {
#Override
public void onTick(long l) {
if (j[0] == 0) {
textView.setText(lyric.getLyricText());
j[0] = 1;
}
}
#Override
public void onFinish() {
textView.setText("");
j[0] = 0;
}
}.start();
}
}
I am not 100% clear what you are trying to achieve but your onTick() method is supposed to run every second until it reaches lyric.timeinMillis(). Based on your condition it runs only the first time (since you change the first cell of the vector to 1).
Im trying to make CountDownTimer start few times in a loop but it only starts one time and it should start at least 2 more times,
I've tried for loop and just While(x !=2)
case R.id.tbWait:
if (waiting.isChecked()){
int x = 0;
do {
turnOnLights();
new CountDownTimer(2000, 1000){
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish(){
turnOffLights();
}
}.start();
x++;
} while (x !=2);
}
break;
I have tried this aswell but it makes the application not responsive and have to force close it :(
case R.id.tbWait:
while (waiting.isChecked()){ //Using While instead of if statemnt
turnOnLights();
new CountDownTimer(2000, 1000){
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish(){
turnOffLights();
}
}.start();
}
break;
Question is how do i loop this when i Toggle the Toggle Button tbWait on?
turnOnLights() then wait 2 seconds then turnOffLights() like the waiting button in the car ? sorry for my bad english and im really new to this ^^
im using AndroidStudio
Do it the android way, use a Handler!
Make a Handler, a Runnable to turn the lights on, and a Runnable to turn them off:
public class YourClass extends ProbablySomeClass{
Handler lightsHandler; //The android.os.Handler one, not the java one
Runnable lightsON = new Runnable(){
#Override
public void run(){
if(waiting.isChecked){
turnLightsOn();
lightsHandler.postDelayed(lightsOff, 2000);
}
else lightsHandler.postDelayed(lightsON, 1000);
}
}
Runnable lightsOff = new Runnable(){
#Override
public void run(){
turnLightsOff();
lightsHandler.postDelayed(lightsON, 2000);
}
}
public YourClass(SomeType someParameter){
init(someParameters); //Whatever your constructor does
lightsHandler = new Handler();
lightsHandler.post(lightsOn)
}
Now all your button has to do is un/check that variable, and it will automatically flash every 2 seconds while it is checked.
I am new to countdown timer so I have no idea about this issue. I tried many things but I didn't get what I expected.
This is my code for the timer. It is a class within a class as usual.
// TIMER
public class Timer extends CountDownTimer {
public Timer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
//getNgo(true, score, tries, secLeft);
}
#Override
public void onTick(long millisUntilFinished) {
//secLeft = millisUntilFinished;
int sec = (int) (millisUntilFinished / 1000);
sec = sec % 60;
int min = sec / 60;
tvTime.setTextColor(Color.WHITE);
if (sec <= 10) {
animScale(tvTime);
tvTime.setTextColor(Color.RED);
tvTime.setText("" + min + ":" + sec);
if (sec < 10) {
tvTime.setTextColor(Color.RED);
tvTime.setText("" + min + ":0" + sec);
}
} else {
tvTime.setText("" + min + ":" + sec);
}
}
}
So, I just wanted to know how to deduct 3 seconds (that will be 3000 ms) when I push the button and the timer that is displayed by the textview will go on ticking but the time has already been deducted. And where do I put the code. Thanks!
When I've had to do this with tasks scheduled to take place in a fixed time, I've:
Cancelled the original task.
Submitted a new one with the new time period.
I suspect that this is a more standard pattern than your use of Timer anyway.
e.g.:
private final Runnable task = new Runnable() { #Override public void run() { /* ... */ } };
private final ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor();
private final long initialSeconds = 3;
public void submitTask() {
stpe.schedule(task, initialSeconds, TimeUnit.Seconds());
}
public void subtractSeconds(long sec) {
if(stpe.remove(task)) {
stpe.schedule(task, Math.Max(initialSeconds - sec, 0), TimeUnit.Seconds);
}
}
You will need to figure out:
how to ensure task is only initially-submitted once and keep track of fixed variable
whether you need one fixed final task or that task to be changed
concurrency/multithreading issues if the task can be submitted more than once
I've implemented a simple countdown using one of the stackoverflow posts
// gets current time
long timeNow = System.currentTimeMillis();
/* timer holds the values of the current second the timer should display
* requiredTime is the start value that the countdown should start from
* startTime is the time when the application starts
*/
timer = requiredTime - (timeNow - startTime) / 1000;
if (timer >= 0)
timer.setText(String.valueOf(timer));
To subtract the timer, subtract requiredTime and it will work. Because you've changed the reference value.
// Override onClickListener and add the line
// to deduct 3 seconds
requiredTime -= 3;
You can't. You have to write your own CountDownTimer. Copy original code and add method
public synchronized void addTime(long millis) {
mStopTimeInFuture += millis;
}
Then set onClickListener to the button
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.addTime(-2000);
}
});
Here is full sample code
I want to create a countdown clock in GWT but I cannot find the right function that waits for one second. I tried with Thread.Sleep() but I think it is for another purpose.
Can you help me? This is my code.
int count=45;
RootPanel.get("countdownLabelContainer").add(countdown);
for(int i=count; i>=0; i--)
{
countdown.setText(Integer.toString(i));
// Place here the wait-for-one-second function
}
Give Timer a try (See Here).
Changing the example code real quick to something close to what you want, you'll want to buff this up for your purposes though:
public class TimerExample implements EntryPoint, ClickListener {
int count = 45;
public void onModuleLoad() {
Button b = new Button("Click to start Clock Updating");
b.addClickListener(this);
RootPanel.get().add(b);
}
public void onClick(Widget sender) {
// Create a new timer that updates the countdown every second.
Timer t = new Timer() {
public void run() {
countdown.setText(Integer.toString(count));
count--;
}
};
// Schedule the timer to run once every second, 1000 ms.
t.schedule(1000);
}
}
This sounds like something in the general area of what your looking for. Note that you can use timer.cancel() to stop the timer. You'll want to tie this in with your count (when 45 hits 0).
The following snippet showing the use of the timer works too. It shows how to schedule the timer properly and how to cancel it.
// Create a new timer that updates the countdown every second.
Timer t = new Timer() {
int count = 60; //60 seconds
public void run() {
countdown.setText("Time remaining: " + Integer.toString(count) + "s.");
count--;
if(count==0) {
countdown.setText("Time is up!");
this.cancel(); //cancel the timer -- important!
}
}
};
// Schedule the timer to run once every second, 1000 ms.
t.scheduleRepeating(1000); //scheduleRepeating(), not just schedule().