Im back to ask another question :)
In an app I am making, I need a selector to choose one of 4 different countdown timers, for example round1, round2, etc.
but i have 2 problems with the same source. Using the default countdowntimer implentation which doesnt involve naming it round1 but running as a straight countdowntimer, I can cancel it in onPause using
coutdowntimer.cancel();
but after naming it round1 I can no longer pause it and the round1.cancel(); comes up as undefined.
I have spent most of yesterday and throught to 3am trying to find a solution and i thought i had it by making my timers final but it still didnt work.
after thinking about it more i relaised once ive solved this problem, I'm going to have to implement an if statement in my onpause which i would rather not do in an effort to keep my code clean.
So is there a way to implement a universal cancel command to cancel the root countdowntimer function regardless of the actual name its running under.
for example
public void canceltimers(){
//if round1,2,3,4 is runnng, cancel the main countdowntimer thread altogether.
countdowntimer.Cancel();
}
any help is appreciated and here is my current timer code.
CountDownTimer round1 = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
textview4.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
endsequence();
}
};
CountDownTimer round2 = new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
textview4.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
endsequence();
}
};
// round1.start();
ive not implemented my if statements for the level select yet but will be similar to this
if (level == 1){
round1.start();}
if (level == 2){
round2.start();}
So far i have tried setting it as final, with no joy.
I have tried
round1.cancel();
with no joy. as well every implementation of countdowntimer i can think of or find.
Now as a request, im not as amazing as making sense of code as most of you guys so if you could try and give an example of the implementation it would be appreciated, Thanks for looking and thanks for your time & help
phil
make a single timer. Add multiple timertasks to this timer. Define the COUNTDOWN_TIME.
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
//execute code when the COUNTDOWN_TIME has ran out.
}
}, COUNTDOWN_TIME);
}
//cancels all sceduled/running TimerTasks
mTimer.cancel();
Related
I have a problem with countdown timer.I try some of solutions and articles in this site but they never worked for me. so, please read my codes...
also I used
handler.postDelayed(new Runnable() {
before and it was not my solution but it just worked correctly.
Main question is:
I want to do something like below:
(button pressed)
do some codes1
delay1
do other codes2
delay2
go back to *do some codes1* again.
In short, this is my real code:
itimesec--;
setdelay();
irepeat--;
setrelax();
and this is in my functions:
public void setrelax(){
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
itotalsnozee--;
TextToSpeechFunction(" "+itotalsnozee);
}
public void onFinish() {
itotalsnozee=fitotalsnozee;
isrelax=false;
TextToSpeechFunction("do again");
}
}.start();
yourCountDownTimer1.cancel();
}
I tried to use a variable insted of 50000 but it was not useful anyway.
I tried to put setrelax funtion codes directly into oncreate but it never worked.
it just jumped to
}.start();
yourCountDownTimer1.cancel();
every times and go out.
I tried all the codes without any delay function and they runned correctly.
what is my wrong please...
You need to remember that your code won't be executed sequentially when using the CountDownTimer because it's working asynchronously (via Handler).
Let's dissect your code. Your following code here:
public void setrelax(){
// 1. Creating CountDownTimer
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
// 2. onTick called
...
}
public void onFinish() {
// 3. onFinish called
...
}
}.start();
// 4. CountDownTimer is cancelled.
yourCountDownTimer1.cancel();
}
will be running in the following sequences:
Creating CountDownTimer
CountDownTimer is cancelled.
onTick called 49 times repeatedly (50000/1000 = 50 - 1 ).
onFinish called
So, change your algorithm to something like this:
do some codes1
delay1
--> When delay finished, do other codes2. Then do delay2
You need to call the next code in the CountDownTimer.onFinish()
I looked at your code and I could not find any big mistakes but try this instead
Instead of
.start();
use
yourCountDownTimer1.start();
and remove yourCountTimer1.cancel();
like this :
public void setrelax(){
CountDownTimer yourCountDownTimer1 = new CountDownTimer(50000, 1000) {
public void onTick(long millisUntilFinished1) {
itotalsnozee--;
TextToSpeechFunction(" "+itotalsnozee);
}
public void onFinish() {
itotalsnozee=fitotalsnozee;
isrelax=false;
TextToSpeechFunction("do again");
}
};yourCountDownTimer1.start();
}
Hope it helps.
below is the code for running otp timer in our code.you can copy paste i have mentioned the comments please follow the same.
CountDownTimer countDownTimer; //define countDownTimer
countDownTimer.start(); // start countdown timer on some event like on click
String x="Your code will expire In";
String y="mins";
counttimer(); call the method counttimer which includes all the code of timer
public void counttimer(){
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
String text = String.format(Locale.getDefault(), x+" %02d : %02d "+y,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
phonever_timer.setText(text); //set timer into textview object
}
public void onFinish() {
phonever_timer.setText("Otp Expired..!");
}
};
I'm new on android application and i'm creating an app that shows a video using a VideoView, I use a CountDownTimer to search each 15 seconds for video updates and play another video. My app works very well during 2 or 3 hours but after this my app just stop, the application doesn't close but is stopped and I must close and open again. What should I do? Thanks.
It literally stops on the screen, it stops the timer and video view.
Here is the code that i'm using to count time to call functions to show video and time.
new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
time++;
downloadTime++;
if(downloadTime == 2){ // Should be executed each 2 seconds
DoDownloads();
downloadTime = 0; //
}
showPlayer();
showTime();
}
public void onFinish() {
this.start();
}
}.start();
I can't show any log because this happens after some hours and can be 2 hours or 10 hours, and i'm testing on tablet.
We would need the code of the rest of your functions, like DoDownloads(); showPlayer(); showTime();
anyways, i wouldnt restart the countdown that way. Id try with a handler and postdelayed(Runnable), like:
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
time++;
downloadTime++;
if(downloadTime == 2){ // Should be executed each 2 seconds
DoDownloads();
downloadTime = 0; //
}
showPlayer();
showTime();
handler.postDelayed(this, tiempo);
}
};
handler.postDelayed(runnable, tiempo);
And also, you should debug the app and copy/past the log cast in the moment it fails, and give us some information about in what point the execution wsa
Is there a way to continuously loop through a countdown timer? I have a basic timer of going though 60 seconds, then updating a text field and it's working, but I want to add the functionality: when it's counted down, to automatically restart again until the user cancels it? Maybe run it through a thread? Not sure how to handle it. Here is what I have, and again, this code works, but I can only stop and start the countdown timer, not do a continuous loop:
cdt = new CountDownTimer(60000,1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText("remaining : " + millisUntilFinished/1000 + " secs");
}
public void onFinish() {
tvTimer.setText("");
bell.start();
}
};
/***************On Click/Touch Listeners*******************/
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tvTimer.setText("");
btnStart.setText("Start Timer");
SetImageView2(myDbHelper);
cdt.cancel();
}
});
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!TimerTicking){
cdt.start();
btnStart.setText("Stop Timer");
}
else {
tvTimer.setText("");
cdt.cancel();
btnStart.setText("Start Timer");
}
}
});
One very basic way to loop a CountDownTimer is to call start() in onFinished().
public void onFinish() {
...
start(); // Start this timer over
}
(Make sure you cancel your CountDownTimer in onPause() when you do this otherwise the timer might leak and keep firing in the background... Oops.)
However CountDownTimers has fundamental flaws (in my opinion): it often skips the last call to onTick() and it gains a few milliseconds each time onTick() is called... :( I re-wrote CountDownTimer in a previous question to be more accurate and call every tick.
The first value to the CountDownTimer() constructor, the total time to run, is a long and can hold a value approaching 300 million years. That ought to be long enough for most mobile applications. :-)
So just call it with cdt = new CountDownTimer(Long.MAX_VALUE, 1000) for a one second loop that will run continously.
I am working on a mini game for Android. I am using this code to create a 3 minute timer that pauses when the game is paused:
class update extends Thread{
#Override
public final void interrupt(){
super.interrupt();
}
#Override
public void run(){
try{
while(true){
sleep(50);
iTime++;
if(iTime>=3600)
bEnd = true; //finish
postInvalidate();
}
}catch(InterruptedException e){
}
}
}
update thread = null;
3600 = 20*3*60
The timer finishes in the emulator within about 5 minutes, and in the Galaxy Tab after about 1.5 minutes.
Why doesn't it always take 3 minutes? How do I ensure that it finishes within 3 minutes?
How about using the Android CountDownTimer class?
// 30 second countdown
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
I am not sure what are you doing in the postInvalidate() but maybe you can do something with AlarmManager and a service. You could create a task that will run in 3 minutes from now, and it will execute the service which, in your case, will invalidate the game.
I've seen many questions that were trying to handle timeouts with sleep method and I believe Android doesn't guaranteed that it will work that way.
Post back if you need help creating the service or running something with AlarmManager. I answered a question about it a couple of days ago.
I'd like to implement several timers (to create a multiple-stopwatches application), and CountDownTimer seems to be the obvious choice, however I'd like to provide the ability to pause one or all of the stopwatches.
From the documentation provided on CountDownTimer I don't see an obvious way to pause the countdown after it has begun, only to stop it or to increase/decrease it by a set amount.
Thanks!
I don't know much about using the CountDownTimer but I know that when I had to make a timer I used the built in Java Timer class with a TimerTask. If you were wanting to make several timers count down and pause them individually you could do something like this
task1 = new TimerTask() {
public void run() {
time1--;
}
};
task2 = new TimerTask() {
public void run() {
time2--;
}
};
Timer1 = new Timer();
Timer2 = new Timer();
Timer1.scheduleAtFixedRate(task1,0,1000);
Timer2.scheduleAtFixedRate(task2,0,1000);
#Override OnClickListener(stopButton1)
{
Timer.Cancel();
}
#Override OnClickListener(startButton1)
{
Timer1 = new Timer();
Timer1.scheduleAtFixedRate(task1,0,1000);
}
This isnt exact syntax but I think it relays the idea. Just a heads up but if you go this route you can't update the UI in that task normally, that would look like this.
Activity_name.this.runOnUiThread(new Runnable() {
public void run() {
text.setText("Level " + Integer.toString(level)+ " will start in " +Integer.toString(time) + " seceonds." );
}
});
which you would put in the "Run" part of the task. This doesn't really have to do with the exact question but I was stuck for days on updating the UI part until someone here helped me out.
I started out using CountDownTimer (but switched to Runnable and Handler.postDelayed).
On timer ticks I decremented a counter. To pause, I canceled the timer. To resume, I created a new timer using the saved counter value. It seemed a little kludgy, but it seemed the only option.
(I don't recall why I made the switch, unfortunately. IIRC at the time there was a reason, but I don't know if it was a limitation of CountDownTimer, or my particular needs.)