How to use a variable for running count down timer? - java

I was creating a timer app and I wanted to use CountdownTimer on Android Studio with a variable . It was showing no error , but on run-time it is (CountdownTimer) running only one time.
int set=1;
final long totalTime=(hour*60)+min;
if(set==1){
new CountDownTimer(totalTime , 1000){
#Override
public void onTick(long millisUntilFinished) {
long min=millisUntilFinished/1000;
Log.i("Remaining time", String.valueOf(min));
}
#Override
public void onFinish() {
}
}.start();

May be if you pass totalTime in ms like..
final long totalTime=(hour*60)+min; //In min convert to ms
long totalTimeInMs = ((hour*60)+min)*60*1000)
new CountDownTimer(totalTimeInMs , 1000){
#Override
public void onTick(long millisUntilFinished) {
long second = millisUntilFinished/1000;
long min = millisUntilFinished/60;
Log.i("Remaining time", String.valueOf(min));
}
#Override
public void onFinish() {
}
}.start();

CountDownTimer ctor expects two time intervals millisInFuture and countDownInterval, both in milliseconds. So:
final long totalTimeInMinutes=(hour*60)+min;
final long totalTime=totalTimeInMinutes * 60 * 1000;

Related

TextView stops updating after a while using hourglass tick function

// After running for a few minutes the UI stop updating inside of the tick function.
//This is update function of my text view in given below
private void timerGreen(final long time, long interval) {
hourglassGreen = new Hourglass(time, interval) {
#Override
public void onTimerTick(long timeRemaining) {
updateUIGreen(timeRemaining);
if (soundrunning) {
soundTick = new SoundTick();
soundTick.playSound(MainActivity.this);
}
}
#Override
public void onTimerFinish() {
}
};
}
// here it is my textview call in my function
private void updateUIGreen(long timeRemain) {
greenTextView.setText(correctFormat(timeRemain));
}
//here my correctFormat method
public String correctFormat(long millisUntilFinished) {
int minutes = (int) (millisUntilFinished / 1000) / 60;
int secs = (int) (millisUntilFinished / 1000) % 60;
return String.format(Locale.getDefault(), "%02d:%02d", minutes, secs);
}

How to make a timer which executes for certain amount of time

I'm in the middle of a Football Match Timer project. Basically, I'm looking for an implementation of a timer which starts after pushing a "START 1st half" button, counts to 45 minutes, than pauses and we are able to start it again pushing "START 2nd half"(it would be the same button, but its text would be changed through the whole match). Then it would count from 45 minutes to 90 minutes.
I've been trying to accomplish this using Handler(), Runnable() and onClickListener(), but it doesn't work at all for me :( Would you give me some suggestions about how to tackle this?
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
showTimeRemaining();
timerHandler.postDelayed(this, 500);
}
};
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
startButton(v);
if (b.getText().equals("Mecz trwa")) {
timerHandler.removeCallbacks(timerRunnable);
b.setEnabled(true);
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("Mecz trwa");
b.setEnabled(false);
}
}
});
public void showTimeRemaining() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView = (TextView) findViewById(R.id.time);
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
}
Here are some of my suggestions.
First, encapsulate your Handler into a class called Timer. This way it's easier to manipulate your timers. Here is my version:
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
#Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
Secondly, don't use System.currenTimeMillis. Use something more manipulatable. Create a variable of your own that stores how many seconds are left:
private int secondsLeft = 60 * 45;
You decrement this variable every second, until it reaches zero. Then, you stop the timer, change the button's text or whatever. This logic should be put into the Runnable used for the handler.
I would suggest to try using of CountDownTimer.
Refer here for documentation and usage:
https://developer.android.com/reference/android/os/CountDownTimer.html

Countdown Timer for android

Can anybody here help me with this code? It's working but when the countdown timer is finished it closes down my apps. I want it to display "finish" on text. But the coding for onFinish that I have used seems not workable.
public class SimpleCountdowTimer extends CountDownTimer {
public static int oneSecond = 1000;
TextView statusTextView;
ProgressBar mprogressBar, mprogressBar1;
Button startTimerButton;
Button stopTimerButton, pauseTimerButton, resumeTimerButton;
private long timeRemaining = 0;
public SimpleCountdowTimer(long millisInFuture, long countDownInterval,
TextView statusTextView, ProgressBar mprogressBar, ProgressBar mprogressBar1) {
super(millisInFuture, countDownInterval);
this.statusTextView = statusTextView;
this.mprogressBar1 = mprogressBar1;
this.mprogressBar = mprogressBar;
}
#Override
public void onTick(long millisInFuture) { //do something in every tick
//Put count down timer remaining time in a variable
statusTextView.setText(String.valueOf(millisInFuture/ oneSecond));
long millis = millisInFuture;
timeRemaining = millisInFuture;
long countDownInterval = 1000;
mprogressBar1.setProgress((int) (millisInFuture));
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
statusTextView.setText(hms);//set text
}
#Override
public void onFinish() {
statusTextView.setText("00:00:00");
mprogressBar.setVisibility(View.VISIBLE);
mprogressBar1.setVisibility(View.VISIBLE);
//Disable the pause, resume and cancel button
pauseTimerButton.setEnabled(false);
resumeTimerButton.setEnabled(false);
stopTimerButton.setEnabled(false);
//Enable the start button
startTimerButton.setEnabled(true);
}
}
Why don't you use this way :
CountDownTimer cdt = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
statusTextView.setText(String.valueOf(millisInFuture/ oneSecond));
long millis = millisInFuture;
timeRemaining = millisInFuture;
long countDownInterval = 1000;
mprogressBar1.setProgress((int) (millisInFuture));
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
statusTextView.setText(hms);//set text
}
#Override
public void onFinish() {
statusTextView.setText("00:00:00");
mprogressBar.setVisibility(View.VISIBLE);
mprogressBar1.setVisibility(View.VISIBLE);
//Disable the pause, resume and cancel button
pauseTimerButton.setEnabled(false);
resumeTimerButton.setEnabled(false);
stopTimerButton.setEnabled(false);
//Enable the start button
startTimerButton.setEnabled(true);
}
};
cdt.start();

What method do i call to start the countdown timer "AccurateCountDownTimer"

as seen in Sam's post on
here, I am unsure what method to use to start the countdown timer "AccurateCountDownTimer".
It will be called from a button (onClick) which is easily set up later.
And the Time remaining will be displayed on a text view.
Here is my code:
public abstract class AccurateCountDownTimer {
public AccurateCountDownTimer(long millisInFuture, long countDownInterval) {
long seconds = (millisInFuture / 1000);
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
// ************AccurateCountdownTimer***************
mTickCounter = 0;
// ************AccurateCountdownTimer***************
testTimer.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
}
/**
* Cancel the countdown.
*/
public final void cancel() {
mHandler.removeMessages(MSG);
}
/**
* Start the countdown.
*/
public synchronized final AccurateCountDownTimer start() {
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mNextTime = SystemClock.uptimeMillis();
mStopTimeInFuture = mNextTime + mMillisInFuture;
mNextTime += mCountdownInterval;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG), mNextTime);
return this;
}
/**
* Callback fired on regular interval.
*
* #param millisUntilFinished
* The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);{
}
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
private static final int MSG = 1;
// handles counting down
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
synchronized (AccurateCountDownTimer.this) {
final long millisLeft = mStopTimeInFuture - SystemClock.uptimeMillis();
if (millisLeft <= 0) {
onFinish();
} else {
onTick(millisLeft);
// Calculate next tick by adding the countdown interval from the original start time
// If user's onTick() took too long, skip the intervals that were already missed
long currentTime = SystemClock.uptimeMillis();
do {
mNextTime += mCountdownInterval;
} while (currentTime > mNextTime);
// Make sure this interval doesn't exceed the stop time
if(mNextTime < mStopTimeInFuture)
sendMessageAtTime(obtainMessage(MSG), mNextTime);
else
sendMessageAtTime(obtainMessage(MSG), mStopTimeInFuture);
}
}
}
};
}
I am not sure if i understand your question... Do you ask how to use this class? I think it will be enough to start timer like this:
new AccurateCountDownTimer(millisInFuture, countDownInterval).start();
Edit: And also you can have callbacks like explained in source code:
new AccurateCountDownTimer(millisInFuture, countDownInterval) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Android: Count Down Timer e.g. 10:00 to 00:00? using OnclickListener to TextView?

I'm trying to make a countdown timer starting at 10 minutes, similair to a basketball scoreboard: 10:00 to 00:00. How would I do that? This is my code:
private TextView Timer;
Handler handler = new Handler();
private int length = 120000;
private int decision = 0;
MyCount counter;
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String sec = String.valueOf(seconds);
String min = String.valueOf(minutes);
if (seconds < 10)
sec = "0" + seconds;
if (minutes < 10)
min= "0" + minutes;
output = min + " : " + sec;
return output;
}//formatTime
#Override
public void onCreate(Bundle cute) {
super.onCreate(cute);
counter = new MyCount(length, 1000);
updateTime();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
}//end of cuteness
private Runnable updateTimeTask = new Runnable() {
public void run() {
updateTime();
handler.postDelayed(this, 1000);
}
};
private void updateTime() {
switch (decision) {
case 0:
startTime = 0L;
counter.start();
decision=1;
break;
case 1:
counter.onPause();
decision=0;
break;
}
}//updateTime
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}//MyCount
public void onPause() {
//do stuff later
onPause();
}//finish
public void onTick(long millisUntilFinished) {
Timer.setText("" + formatTime(millisUntilFinished));
}//on tick
#Override
public void onFinish() {
onStop();
}//finish
}//class MyCount
Any help would be appreciated. thanks!
This does not have to be too hard. You've already created your functionality for writing your time in letters, now you need to count down. Starting a timer is easy, just do this in your start button event handler (or whatever you choose to use) (modified example from the android developer reference:
// New timer for 10 minutes, starts after initialization
new MyCount(600000, 1000)
{
// Updates the text on your "scoreboard" every second
public void onTick(long millisUntilFinished)
{
Timer.setText("Time remaining: " + formatTime(millisUntilFinished));
}
public void onFinish()
{
mTextField.setText("done!");
}
}.start();
And that's all you need! You can skip your UpdateTime function and your updateTimeTask. Just replace all this on your onCreate method
counter = new MyCount(length, 1000);
updateTime();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
With my code. Or modify it as you please!
why don't you just create 3 textviews so that it will be easier for you to code?
one for the minutes.
one for the colon.
one for the seconds.
then use the code he's using.
hope I helped.
The way i think of making a count down is just saving at the beginning the (current time + 10 minutes) aside and then just subtract it from current time every second in your handler and display the result in the desired format..

Categories

Resources