I ran across an issue, I'm using a count down timer in a method as shown below, and call it at certain places in my application i.e. scoreTimer(); I'm having a hard time figuring out how to stop it, I noticed a .start() method at the end of CountDownTimer and I assume there should be a .stop() method as well, but how can I apply it when I use a method - scoreTimer()?
public void scoreTimer() {
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
getTimer.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
cycleState = 1;
expressionCycle();
if (currentCycle <= 10) {
scoreTimer();
}
System.out.println("SCORE: " + totalScore);
}
}.start();
}
Assign the timer to a variable like this:
CountDownTimer mTimer = new CountDownTimer...
And then you can invoke
mTimer.cancelTimer()
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 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 would like to create a stopwatch as an android app. My problem is that I got a stackoverflow. Basically I have a class Timer and an onCreate method that instatiate it. Thats my implementation:
public abstract class Timer implements Runnable {
private boolean running;
public void start(){
running = true;
this.start();
}
#Override
public void run() {
long milliSeconds = 0;
long seconds = 0;
long minutes = 0;
long baseTime = SystemClock.elapsedRealtime();
while(running){
long time = SystemClock.elapsedRealtime() - baseTime;
long rest = time % 60000;
milliSeconds = rest % 1000;
seconds = rest - milliSeconds;
minutes = time - seconds - milliSeconds;
display(milliSeconds, seconds, minutes);
}
}
public void stop(){
running = false;
}
public abstract void display(long milliSeconds, long seconds, long minutes);
}
And my onCreate method:
public TextView time;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.opslimit);
time = (TextView)findViewById(R.id.textView3);
Timer timer = new Timer(){
#Override
public void display(long milliSeconds, long seconds, long minutes) {
time.setText(minutes + ":" + seconds + ":" + milliSeconds);
}
};
timer.start();
}
Has anyone an idea why I got a Stackoverflow. May be it deals with the display part?
You call start method recursively within itself. Fix it, and you won't get SO exception.
Note, however, that even if you change to :
public void start(){
running = true;
this.run();
}
which will fix stackoverflow, your code will run in a main thread and therefore your app won't work. You have to spawn a new thread.
I really suggest you use CountDownTimer - it will be clean code and less boilerplate threading, check example at the link.
You can, however, make your code work by doing this changes :
make Timer extends Thread instead of implementing Runnable.
change start to :
public void start(){
running = true;
super.start(); // <- note super here
}
Optionally add Override notation to start/stop methods, or rename your stop -> stopTimer
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.