Basically I am doing a cardio feature and have three countdown timers in a row nested within each other, so when one timer finishes, the next one starts. One for preparation time, one for workout time and one for rest time, the user chooses the times of these.
I need it to loop however many times the user selects from a numberpicker, but no matter what I do it only goes through it once and doesn't loop so I know it all works it's just the looping part that doesn't work.
Am I missing something here? Is there a better way to do this?
//Main countdown timers loop
for(int i = 0; i <= times.getValue() + 1; i++) //times NumberPicker
{
prepCountTimer = new CountDownTimer(_finalPrep * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvRoundCount.setText("Round " + roundCount + " / " + times.getValue());
tvCountDown.setText((millisUntilFinished / 1000) + "s");
if(millisUntilFinished <= (6 * 1000))
{
tvCountDown.setTextColor(Color.RED);
}
}
public void onFinish() {
workoutCountTimer = new CountDownTimer(_finalWorkout * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvCountDown.setTextColor(Color.GREEN);
tvCountDown.setText((millisUntilFinished / 1000) + "s");
if(millisUntilFinished <= 6 * 1000)
{
tvCountDown.setTextColor(Color.RED);
}
}
public void onFinish() {
restCountTimer = new CountDownTimer(_finalRest * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvCountDown.setTextColor(Color.GREEN);
tvCountDown.setText((millisUntilFinished / 1000) + "s");
if(millisUntilFinished <= 6 * 1000)
{
tvCountDown.setTextColor(Color.RED);
}
}
public void onFinish() {
roundCount = roundCount + 1;
}
}.start();
}
}.start();
}
}.start();
}
the issue here is that you create prepCountTimer and assign on finish ect, then start it. then it reaches the end of for each and loops again making another preopCountTimer and starting it. you need to make your restCountTimer start the next preopCountTimer once it's done. unless I'm understanding something wrong here.
public void callingMethod() {
timerMethod(times.getValue());
// execution continues as your timer will run in a different thread
}
public void timerMethod(final int count) {
if (count == 0) {
// we have done the number of timers we want we can
// call whatever we wanted to once our timers were done
}
//you could use count to get the times for each timer here
startTimer(_finalPrep, new timerListner() {
#Override
public void timerFinish() {
//when timer 1 finishes we will start timer 2
startTimer(_finalWorkout, new timerListner() {
#Override
public void timerFinish() {
//when timer 2 finishes we will start timer 3
startTimer(_finalRest, new timerListner() {
#Override
public void timerFinish() {
//when timer 3 finishes we want to call the next timer in the list.
timerMethod(count - 1);
}
});
}
});
}
});
}
private interface timerListner {
void timerFinish();
}
public void startTimer(int timerTime, final timerListner onFinish) {
// you can pass in other parameters unqiue to each timer to this method aswell
CountDownTimer timer = new CountDownTimer(timerTime * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvRoundCount.setText("Round " + roundCount + " / " + times.getValue());
tvCountDown.setText((millisUntilFinished / 1000) + "s");
if (millisUntilFinished <= (6 * 1000)) {
tvCountDown.setTextColor(Color.RED);
}
}
#Override
public void onFinish() {
onFinish.timerFinish();
}
};
timer.start();
}
Related
In my application i should use CountDownTimer and for this I want use this library : CountdownView.
I want when lasted 5s show me Toast.
For example : I want show 17s countTimer, when this timer receive to 5s show me toast "just 5s".
I use this code, but show me ever 5s .
long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(5000, new CountdownView.OnCountdownIntervalListener() {
#Override
public void onInterval(CountdownView cv, long remainTime) {
Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
}
});
I want just lasted 5s not ever 5s.
how can i it?
By modifying your code:
boolean toastShown = false;
long time1 = 17 * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
#Override
public void onInterval(CountdownView cv, long remainTime) {
if(remainTime < 5000 && !toastShown) {
toastShown = true;
Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
}
}
});
You can try this code also:
CountDownTimer countDownTimer = new CountDownTimer(17000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Toast.makeText(HomeActivity.this, "running" + millisUntilFinished, Toast.LENGTH_SHORT).show();
if (millisUntilFinished < 5000) {
Toast.makeText(HomeActivity.this, "5 sec left", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFinish() {
Toast.makeText(HomeActivity.this, "Countdown Timer Finished", Toast.LENGTH_SHORT).show();
}
};
countDownTimer.start();
I think you should check how many seconds remains.
I rewrote your code:
long time1 = 17L * 1000;
mCvCountdownViewTest1.start(time1);
mCvCountdownViewTest1.setOnCountdownIntervalListener(1000, new CountdownView.OnCountdownIntervalListener() {
#Override
public void onInterval(CountdownView cv, long remainTime) {
long remainTimeInSeconds = remainTime / 1000;
if (remainTimeInSeconds == 5) {
Toast.makeText(MainActivity.this, "Just 5s ", Toast.LENGTH_SHORT).show();
}
}
});
I am creating a game and I put a timer to onCreate method to display time to user and make an action when it reaches to 0. My way works correctly but since I wrote it to onCreate the time continues to count down and if I rotate screen etc it resets the timer seconds. I know why this happens but I could not find a way to stop it when app is paused and make it continue from where it left of when application continues. Here is my code
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
question.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
question.setText("done!");
Intent i2 = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i2);
}
}.start();
Should I save milisUntilFinished to savedInstanceState and make the timer start depending on the savedInstanceState or is there an easier solution
Edit: So I updated my code to reflect the thing I ve asked. This way I can save the last state of timer when the phone is rotated, but timer still does not stop when I open the menu (pause the application.)
if(savedInstanceState!=null){
seconds = savedInstanceState.getInt("seconds");
new CountDownTimer(seconds * 1000, 1000) {
public void onTick(long millisUntilFinished) {
seconds = (int) millisUntilFinished;
question.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
question.setText("done!");
Intent i2 = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i2);
}
}.start();
}else {
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
seconds = (int) millisUntilFinished;
question.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
question.setText("done!");
Intent i2 = new Intent(getApplicationContext(), CategoryActivity.class);
startActivity(i2);
}
}.start();
}
CounDwonTimer mCountTimer;
int seconds = 0;
then just cancel the mCountTimer in onPause and start in `onResme'
protected void onResume(){
super.onReusme();
mCountTimer = new CountDownTimer(seconds*1000,1000){
//......record the seconds
}
}
protected void onPause(){
if(mCountTimer != null)
mCountTimer.cancel();
}
if your activity will destory when rotate the screen,you need onSaveInstanceState.otherwise you do not need this method
I hope the following code will help you,
private long startTime = 0L;
private boolean threadStop = false;
private Handler myHandler = new Handler();
private Runnable updateTimerMethod = new Runnable() {
public void run() {
if (isAdded()) {
timeInMillies = SystemClock.uptimeMillis() - startTime;
//finalTime = timeSwap + timeInMillies;
time.setText(miliSecondToMinSec(timeInMillies));
if (!threadStop)
myHandler.postDelayed(this, 1000);
}
}
};
#Override
public void onStart() {
super.onStart();
if (threadStop) {
threadStop = false;
startTime = SystemClock.uptimeMillis() - timeInMillies;
myHandler.postDelayed(updateTimerMethod, 0);
}
}
#Override
public void onStop() {
threadStop = true;
super.onStop();
}
what I'm trying to do:
My app connects with a Bluetooth accelerometer and gets acceleration data every 50ms. I want to check for these with a Runnable. And this worked fine. However, for the complete app I added two CountDownTimers:
1) introTimer(), which runs in an AlertDialog and counts down from 3. OnFinish() calls (i) my Runnable, that deals with new acceleration data and (ii) a second timer called
2) mainTimer(), which counts down from 20 and refreshes a TextView on the UI.
My problem is, that my Runnable is only executed once when it is first called. Why is that? Apparently I have not yet understood the threading principles behind this. My next step (probably going to be complicated) is to refresh ImageViews every 50ms (or maybe less often, but still with a relatively high frequency) on the UI, depending on the accelerometer data.
I have thought about deleting the Runnable and putting my calculations in the CountDownTimer, but this might be difficult or inaccurate with the timing/frequency/periods. What do you think?
Here are the code parts. If you think other parts are relevant, I can post them as well:
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View promptView = layoutInflater.inflate(R.layout.intro_timer_prompt, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final TextView introTimer = (TextView) promptView.findViewById(R.id.introTimer);
builder.setView(promptView);
AlertDialog alertD = builder.create();
alertD.show();
introTimer(introTimer, alertD);
}
private void introTimer(final TextView introTimer, final AlertDialog alertD) {
new CountDownTimer(4*1000, 1000) {
public void onTick(long millisUntilFinished) {
introTimer.setText( ""+ (millisUntilFinished / 1000));
}
public void onFinish() {
alertD.cancel();
// mainTimer();
clearArrayLists();
mHandler = new Handler();
mHandlerTask.run();
mainTimer();
}
}.start();
}
private void mainTimer() {
new CountDownTimer((int)DURATION*1000, 10) {
public void onTick(long millisUntilFinished) {
//mTimerView.setText("seconds remaining: " + millisUntilFinished / 1000 + ":" + millisUntilFinished / 1000. );
long millisecs = Math.round(millisUntilFinished % 1000 / 100);
mTimerView.setText("seconds remaining: " + millisUntilFinished / 1000 + ":" + millisecs );
}
public void onFinish() {
String energy = new DecimalFormat("#.##").format(accumulatedKineticEnergy.get(accumulatedKineticEnergy.size()-1));
mTimerView.setText("Accumulated Energy is " + energy + " Joule.");
}
}.start();
}
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
Log.i(TAG, "executed only once :( ");
if (a_x.size() < DURATION/INTERVAL) {
try {
calcAccList();
//...calc things...;
mHandler.postDelayed(this, (long) (1000*INTERVAL));
} catch (Exception e) {
e.getMessage();
}
}
else {
mHandler.removeCallbacks(mHandlerTask);
}
}
};
A countdown timer doesn't repeat itself when it expires, but you need to start it again. Maybe you can use the AlarmManager in this case to have a better design.
I have strange problem with countdowntimer. Normally it works well, but sometimes (like 5% chance or so) after locking phone and unlocking it bugs like on video:
https://www.dropbox.com/s/1nbp63gmv4spzgf/bug.mp4
Here i set the timer:
private void startCurrentLessonTimer() {
if(lessonsBreak) {
lessonsBreakEnd.setText(String.format("%02d:%02d:%02d", (currentLessonTimeInMillis / 1000) / 3600, ((currentLessonTimeInMillis / 1000) % 3600) / 60,
(currentLessonTimeInMillis / 1000) % 60));
} else {
currentLessonEnd.setText(String.format("%02d:%02d:%02d", (currentLessonTimeInMillis / 1000) / 3600, ((currentLessonTimeInMillis / 1000) % 3600) / 60,
(currentLessonTimeInMillis / 1000) % 60));
}
currentLessonTimer = new CountDownTimer(currentLessonTimeInMillis, 1000) {
long hours = (currentLessonTimeInMillis / 1000) / 3600;
long minutes = ((currentLessonTimeInMillis / 1000) % 3600) / 60;
long seconds = (currentLessonTimeInMillis / 1000) % 60;
#Override
public void onTick(long millisUntilFinished) {
if(seconds == 0) {
seconds = 59;
if(minutes == 0 && hours > 0) {
minutes = 59;
hours--;
}
else {
minutes--;
}
} else {
seconds--;
}
if(lessonsBreak) {
lessonsBreakEnd.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
} else {
currentLessonEnd.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
}
#Override
public void onFinish() {
getNextLesson();
getCurrentLesson();
}
}.start();
}
And this function (inside getData()) is called in onResume()
#Override
public void onResume() {
super.onResume();
getData();
}
onPause():
#Override
public void onPause() {
super.onPause();
clean();
}
clean():
private void clean() {
if(currentLessonTimer != null) {
currentLessonTimer.cancel();
currentLessonTimer = null;
}
}
I tried to use other countdowntimer, but this problem still occurs (but not that often).
Code: http://pastebin.com/nKsasJ1S
Any ideas?
It looks like you get multiple CountDownTimers refreshing your UI. This leads me to your clean() function like it's not doing it's job on every onPause(). So on next onResume() there will be multiple CountDownTimers.
I don't know how CountDownTimer works but the thing I can think of is that your CountDownTimer is start()ed but still not initialized (currentLessonTimer is still null) when onPause() is occurring not letting clean() to run so it'd be a race condition that could be avoided with a Service for example.
My intention is to create an timer which starts from 00:00:00 and hangs together with a recording function. This recording is done in a service so, the timer is also in the same service. If the app moves to the background, the recording and thus the timer keep on going and the app picks the time up at the onResume with a myService.getTime().
But I experience two strange things. The first is that my timer sometimes goed faster than a second, sometimes slower, sometimes jumps from for example 00:00:04 to 00:00:06 etc. There is no consitency in it. I use the code below, but there might be a better option to solve this? The second is that it is causing a lag on my button, although I am starting it in a service?
SERVICE
//////////TIMER FUNCTION START//////////
private void startTimerClick() {
if (stopped) {
startTime = System.currentTimeMillis() - elapsedTime;
} else {
startTime = System.currentTimeMillis();
}
mHandler.removeCallbacks(startTimer);
mHandler.postDelayed(startTimer, 0);
}
private void pauseTimerClick() {
mHandler.removeCallbacks(startTimer);
stopped = true;
}
private void stopTimerClick() {
mHandler.removeCallbacks(startTimer);
stopped = false;
}
private void startTimer() {
startTimer = new Runnable() {
public void run() {
elapsedTime = System.currentTimeMillis() - startTime;
updateTimer(elapsedTime);
mHandler.postDelayed(this, REFRESH_RATE);
}
};
}
private void updateTimer(float time) {
secs = (long) (time / 1000);
mins = (long) ((time / 1000) / 60);
hrs = (long) (((time / 1000) / 60) / 60);
/*
* Convert the seconds to String and format to ensure it has a leading
* zero when required
*/
secs = secs % 60;
seconds = String.valueOf(secs);
if (secs == 0) {
seconds = "00";
}
if (secs < 10 && secs > 0) {
seconds = "0" + seconds;
}
/* Convert the minutes to String and format the String */
mins = mins % 60;
minutes = String.valueOf(mins);
if (mins == 0) {
minutes = "00";
}
if (mins < 10 && mins > 0) {
minutes = "0" + minutes;
}
/* Convert the hours to String and format the String */
hours = String.valueOf(hrs);
if (hrs == 0) {
hours = "00";
}
if (hrs < 10 && hrs > 0) {
hours = "0" + hours;
}
}
//////////TIMER FUNCTION END////////////
public String getHours(){
return hours;
}
public String getMinutes(){
return minutes;
}
public String getSeconds(){
return seconds;
}
}
ACTIVITY(/FRAGMENT)
private void timerStart() {
handler = new Handler();
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
handler.post(new Runnable() {
#Override
public void run() {
timer.setText(myService.getHours()+":"+myService.getMinutes()+":"+myService.getSeconds());
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
}
You are using Threads both in your Service and in your Activity/Fragment code.
Using threads for time sensitive tasks in Android is a problem because Android is able to significantly delay threads.
I have been using a ScheduledThreadPoolExecutor for a similar task and it worked great.
You are then using it like this:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); // where 1 is the number of needed concurrent threads. 1 should last for your needs.
executor.scheduleWithFixedDelay(new TimerTask() {
// your recurringly executed code here
}, 0, 1, TimeUnit.SECONDS);