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..!");
}
};
Related
I'm creating a quiz app in android. I have written OnClickListener for next button to load next question. now I want to add timer to each question so that when timer ends it will automatically call OnClickListener of next button. How to implement this?
If you want to delay some code from running for a certain amount of time use a Runnable and a Handler like this
Runnable r = new Runnable() {
#Override
public void run(){
doSomething(); //<-- put your code in here.
}
};
Handler h = new Handler();
h.postDelayed(r, 1000);
You just need to call performClick() on an instance of your next button. Something like this:
nextButton.performClick()
That will execute everything you have inside of OnClickListener that is set for that button.
EDIT:
If I misunderstood your question and you are searching for Timer implementation, I recommend for you check CountDownTimer that is provided by Android team. You can check documentation with an example for his here:
https://developer.android.com/reference/android/os/CountDownTimer
You can have a method you call when the user clicks the next button say it's named as nextQuestion()
then add the listener of your next button
Button nextBtn = findViewById(..);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextQuestion();
}
});
And the time would be CountDownTimer of say 1 min duration (60*1000 msec) and 1 second tick (1000 msec)
new CountDownTimer(60000, 1000) { // 1 min duration (60*1000 msec) and 1 second tick (1000 msec)
#Override
public void onTick(long millisUntilFinished) {
// do something each second
}
#Override
public void onFinish() {
// timer expired
nextQuestion();
}
}.start();
I want to make an application about mini game.
Detail : In 2 seconds you must to answer a question if you don't answer or the answer is wrong -> Game Over . But if your answer is true the Timer will reset become 0 and countdown again with diffirent question.
I have already seen many code about timer in website but I don't understand clearly about it :(
So I want to ask : How can i set up a timer run only 2 seconds and how can i reset it and continue with a new question ?
Please help me.
you can use CountDownTimer in android like this:
public class Myclass {
myTimer timer =new myTimer(2000,1000);
public void creatQuestion(){
timer.start();
//method you init question and show it to user
}
public void getUserAnswer(/*evry thing you expected*/)
{
//if answer is true call timer.start()
//else call timer.onFinish(); to run onfinish in timer
}
public class myTimer extends CountDownTimer {
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
// you can update ui here
}
#Override
public void onFinish() {
this.cancel();
//fire game over event
}
}
}
i hope it make you satisfy
I've done something similar using Thread/Runnable.
Thread t = new Thread(new Runnable() {
public void run() {
final long startTime = getTime();
final long maxEndTime = startTime + 2000L;
try {
while (shouldContinueWaiting()) {
if (getTime() > maxEndTime) {
throw new TimeoutException();
}
sleep();
}
} catch (InterruptedException e) {
handleInterrupt();
} catch (TimeoutException e) {
handleTimeout();
}
}
boolean shouldContinueWaiting() {
// Has the user already answered?
}
void handleInterrupt() {
// The user has answered. Dispose of this thread.
}
void handleTimeout() {
// User didn't answer in time
}
void sleep() throws InterruptedException {
Thread.sleep(SLEEP_DURATION_IN_MILLIS);
}
void getTime() {
return System.currentTimeMillis();
}
then you can start/restart the thread by:
t = new Thread(same as above...);
t.start();
and stop by:
t.interrupt();
We want to use the Timer class.
private Timer timer;
When you're ready for the timer to start counting -- let's say it's after you press a certain button -- do this to start it:
timer = new Timer();
timer.scheduleAtFixedRate(incrementTime(), 0, 100);
The first line is us creating a new Timer. Pretty standard. The second line, however, is the one I wanted you to see.
incrementTime() is a method that is called at the end of every "tick" of the clock. This method can be called whatever you want, but it has to return an instance of TimerTask. You could even make an anonymous interface if you want, but I prefer moving it off into its own section of code.
The 0 is our starting location. We start counting from here. Simple.
The 100 is how large a "tick" of the clock is (in milliseconds). Here, it's every 100 milliseconds, or every 1/10 of a second. I used this value at the time of writing this code because I was making a stopwatch application and I wanted my clock to change every 0.1 seconds.
As for your project, I'd suggest making the timer's task be your question switch method. Make it happen every 2000 milliseconds, or 2 seconds.
You can use a Handler.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//this will happen after 2000 ms
}
}, 2000);
Maybe this can help you:
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// FIRE GAME OVER
handler.postDelayed(this, 2000); // set time here to refresh textView
}
});
You can fire your game over after 2000 milliseconds.
If you get the question correct -> remove callback from handler and reset it when the next question starts.
I'm trying to create a countdown timer for my app but after doing this, the TextView where it should show the remaining time doesn't show anything so my timer is not working. I don't know if I am missed something.
Here is my timer:
setContentView(R.layout.layout7);
cronometro = (TextView) findViewById(R.id.cronometro);
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
cronometro.setText(Long.toString(millisUntilFinished / 1000));
}
public void onFinish() {
cronometro.setText("done!");
}
}.start();
Edit: As Simon said and changing some things the timer works now. Is there a way of setting the format into MM:SS
cronometro.setText(DateUtils.formatElapsedTime(millisUntilFinished/1000));
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'm extending the CountDownTimer class to obtain some custom functionality .In onTick() in case some conditions are met I call cancel() , expecting that will be the end of it, however the onTick() callback gets call until the the count down is reached . So how to prevent this from happening ?
CountDownTimer.cancel() method seems to be not working. Here's another thread without a solution Timer does not stop in android.
I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:
public class MainActivity extends Activity {
TextView mTextField;
long elapsed;
final static long INTERVAL=1000;
final static long TIMEOUT=5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextField=(TextView)findViewById(R.id.textview1);
TimerTask task=new TimerTask(){
#Override
public void run() {
elapsed+=INTERVAL;
if(elapsed>=TIMEOUT){
this.cancel();
displayText("finished");
return;
}
//if(some other conditions)
// this.cancel();
displayText("seconds elapsed: " + elapsed / 1000);
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
}
private void displayText(final String text){
this.runOnUiThread(new Runnable(){
#Override
public void run() {
mTextField.setText(text);
}});
}
}
CountDownTimer is also working fine for me, but I think it only works if you call it OUTSIDE of the CountDownTimer implemetation (that is don't call it in the onTick).
Calling it inside also didn't worked.
I tried this code snippet, since most answers are saying you cannot cancel the timer inside its implementation, thus i tried using a handler inside onFinish. Old post but if anyone comes across this its helpful.
new Handler().post(new Runnable() {
#Override
public void run() {
timerTextView.setText("00:" + String.format("%02d", counter));
cancel();
}
});