i have countdown timer with this code:
CountDownTimer CountdownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
txttime.setText( millisUntilFinished / 1000);
}
public void onFinish(){
timeout_stage();
CountdownTimer.cancel();
}
};
i start it with this code:
CountdownTimer.start();
and then i stop it by this code:
CountdownTimer.cancel();
but after cancelling, when i start it again my CountdownTimer works but the text on the txttime is not change!! (but first time works perfectly)
how i can fix it?
Related
I'm developing an application which is a typing test that allows users to test their typing speed by typing a passage in a specific period of time. The problem is that users are still be able to type after that period of time. How would I stop the timer after that specific time in order to stop users from typing?
CountDownTimer cdTimer; cdTimer=new CountDownTimer(30100, 1000) {
public void onTick(long millisUntilFinished) {
timerTextView.setText(String.valueOf(millisUntilFinished / 1000) + "s");
}
public void onFinish() {
playAgainButton.setVisibility(View.VISIBLE);
timerTextView.setText("0s");
}
}.start();
You can do as follow
CountDownTimer cdTimer; cdTimer=new CountDownTimer(30100, 1000) {
public void onTick(long millisUntilFinished) {
timerTextView.setText(String.valueOf(millisUntilFinished / 1000) + "s");
}
public void onFinish() {
<WriteHearActivityName>.this.finish();
startActivity(<WriteHearActivityName>.this,ResultActivity.class);
}
}.start();
This will solve your issue +1
I am making a simple app which uses a count down timer,Circular
progress bar and 3 buttons start, Pause and Resume.What I am trying to
do is when a particular activity starts and I press pause it stores
the time at which the timer was paused and resume from that point
forward.But the problem is the count down timmer doesn't stop so if I
pause at say 7 sec the progress bar stops at 7sec but when I press
resume it starts from whatever the count down timer value is at that
moment.This is the code I am trying to implement.
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//When user request to pause the CountDownTimer
isPaused = true;
//Enable the resume and cancel button
btnResume.setEnabled(true);
//Disable the start and pause button
btnStart.setEnabled(false);
btnPause.setEnabled(false);
}
});
btnResume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Disable the start and resume button
btnStart.setEnabled(false);
btnResume.setEnabled(false);
//Enable the pause and cancel button
btnPause.setEnabled(true);
//Specify the current state is not paused and canceled.
isPaused = false;
isCanceled = false;
mCountDownTimer.start();
}
});
And this is code for the count down timer.
private void neck_rotations()
{
neckRotation = true;
mCountDownTimer = new CountDownTimer(NECK_ROTATION_TIME, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
if (isPaused || isCanceled)
{
paused_at = (int) (millisUntilFinished / 1000);
} else
{
timeRemaining = (int) (millisUntilFinished / 1000);
donutProgress.setMaxValue(NECK_ROTATION_TIME / 1000);
donutProgress.setValueAnimated((int) timeRemaining);
counter.setText(String.valueOf(timeRemaining));
}
}
#Override
public void onFinish()
{
response = "Jumps";
rest(response);
}
};
mCountDownTimer.start();
}
I am new to programming so any help or suggestion is appreciated.Thank you.
Please refer to this:
How to clear CountDownTimer from onTick method?
I'm not sure you can disable the timer from still counting down from the inner onTick() method.
Make a gloabl reference for the CountDownTimer and only call start() or cancel() from the clickListeners on that reference.
I am trying to use countdowntimer in Android, following is a small testcode to understand its behaviour
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
System.out.println("tick");
}
public void onFinish() {
System.out.println("finish");
}
}.start();
System.out.println("done");
If I place this snippet in MainActivity of my project it runs fine, but not in a standalone class. Why ?
Also, does countdown timer run on main thread itself, or it spawns another thread ?
Your code includes 2 parts:
CountDownTimer cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
System.out.println("tick");
}
public void onFinish() {
System.out.println("finish");
}
};
The first part is instantiating a CountDownTimer object, you can place this code any where, on any thread, because only object was created, it does nothing.
The second part is:
cdt.start();
You should notice that CountDownTimer must be start from Main Thread (call it from onCreate or onResume... of an Activity). So if you place your code in another Class, it is not the problem, you must sure that start() function called on Main Thread.
//Update:
You know, the onTick and onFinish function of CountDownTimer always is called on Main Thread. CountDownTimer will not run any thread.
It's its code:
public synchronized final CountDownTimer start() {
mCancelled = false;
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
Very simply, CountDownTimer will send a message by a Handler.
And this is Handler:
// handles counting down
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
if (mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// special case: user's onTick took more than interval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
The Handler will send a delay message for calling next onTick() or onFinish(). So it must use Main Thread (or Main Looper). If you want it run in a custom thread, reimplement it in your way :D
I am writing an HIIT (High Intensity Interval Training) activity for which I am implementing an interval timer. The CountDownTimer is supposed to finish 5 minutes of Warm-Up, then proceed to time the HIIT workout.
public class WarmUpActivity extends ActionBarActivity{
TextView Mode;
TextView Time;
int minutes;
long time_remaining;
boolean warmup_finished;
private CountDownTimer HIIT_Timer;
private void StartTimer() {
HIIT_Timer = new CountDownTimer(time_remaining, 1000) {
#Override
public void onTick(long millisUntilFinished) {
time_remaining = millisUntilFinished; //in case activity is paused or stopped
Time.setText(" " + (int)floor(millisUntilFinished / 60000) + ":" + ((millisUntilFinished / 1000) % 60));
if (warmup_finished == true) { //if we are in HIIT mode
if ((int)millisUntilFinished % 60000 == 0) { //every minute
if (Mode.getText() == "Low Intensity")
Mode.setText("High Intensity");
else
Mode.setText("Low Intensity");
}
}
}
#Override
public void onFinish() {
if (warmup_finished==false){
Mode.setText("Low Intensity");
warmup_finished = true;
HIIT_Method();
return;
}
else {
Completed_Method();
return;
}
}
}.start();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hiit_layout);
Mode=(TextView) findViewById(R.id.mode);
Time=(TextView) findViewById(R.id.time);
warmup_finished=false;
Mode.setText("Warm-Up");
time_remaining=5*60000; //5 minutes when created
}
#Override
public void onStart(){
super.onStart();
StartTimer();
return;
}
private void HIIT_Method(){
minutes=getIntent().getIntExtra(SelectHIITDuration.MINUTES, 0);
time_remaining=minutes*60000;
StartTimer();
return;
}
private void Completed_Method(){
Mode.setText("Workout Completed");
}
}
When warmup is finished and onFinish() is called for the first time, HIIT_Method is called, in which the HIIT timer is supposed to start with user specified duration. The problem is, after the new timer is declared using Start_Timer(), somehow Completed_Method is called. It can only be called from onFinish(). Why is onFinish() being called after I declare a new timer?
We need to move your call to startTimer from onStart to onCreate.
The issue here is understanding the Android lifecycle for an activity. A very good explanation by someone with better understanding than I is explained here.
Now from what I understand, we typically don't touch onStart until we start worrying about service binding and database queries, but other developers may think differently.
The official android documentation on an activity's lifecycle can be found here
I am looking for simplest way to close opened activity after x minutes. Does android provide countdown class or do I have to made one by my self ?
I've tried this code but its not working
Thread isOnDisplayThread = new Thread(new Runnable() {
#Override
public void run() {
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG, (isApplicationOnDisplay) ? "Application on display" : "APPLICATION ON BACKGROUND");
if (!isApplicationOnDisplay) {
notOnDisplayTime++;
if (notOnDisplayTime >= 10) {
Process.killProcess(Process.myPid());
}
} else {
notOnDisplayTime = 0;
}
}
}, 0, 1000);
}
});
isOnDisplayThread.run();
Handler handler = new Handler();
Runnable r=new Runnable() {
#Override
public void run() {
finish();
}
};
handler.postDelayed(r, 2000);
Never ever ever ever ever* call the run() method of a Java Thread. Call its start() method, which causes Java to call its run() method for you within the new thread.
Bad idea:
Process.killProcess(Process.myPid());
You should call finish() function in UI thread. For example, use runOnUiThread(): link
It is not working because you are calling the run method. It will not start the thread.
So you need to call the start method to invoke the thread
isOnDisplayThread.start();
Also to finish off the thread you need to call the
finish() ///method of the Activity class
If the code is with in the Activity class then just call the finish() method
if (notOnDisplayTime >= 10) {
finish();
}
private final long startTime = 200000;
private final long interval = 1000;
countDownTimer = new MalibuCountDownTimer(startTime, interval);
countDownTimer.start();
public class MalibuCountDownTimer extends CountDownTimer{
public MalibuCountDownTimer(long startTime, long interval){
super(startTime, interval);
}
#Override
public void onFinish(){
txttimer.setText("Time's up!");
//timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished) {
//text.setText("Time remain:" + millisUntilFinished);
//timeElapsed = startTime - millisUntilFinished;
String format = String.format("%%0%dd",2);
String seconds = String.format(format, millisUntilFinished/1000 % 60);
String minutes = String.format(format, (millisUntilFinished /(1000*60))%60);
String hours = String.format(format, (millisUntilFinished /(1000*60*60))%24);
String time = hours + ":" + minutes + ":" + seconds;
txttimer.setText("Time Remaining:" + time);
TimeUnit.MILLISECONDS.toMinutes(timeElapsed) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeElapsed)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeElapsed)));
System.out.println(hms);
//text.setText("Time remain:" + h+":"+m+":"+s);
//timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
Declare the Timer and Call finish(). It will close your activity after certain time.
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.schedule(new TimerTask() {
#Override
public void run() {
finish();
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
Simply use Handler.postDelayed method.