Although there are answered questions about this, none REALLY answers the following:
I want the android chronometer to start from the last stop, NOT to continue counting time.
I try the following, but IT DOES NOT WORK :-(
public class MainActivity extends ActionBarActivity {
long stopTime = 0;
public void startChronometer(View view) {
long elapsedTime = SystemClock.elapsedRealtime() - stopTime;
((Chronometer) findViewById(R.id.mycrono)).setBase(elapsedTime);
((Chronometer) findViewById(R.id.mycrono)).start();
}
public void stopChronometer(View view) {
stopTime = findViewById(R.id.mycrono).getBaseline();
((Chronometer) findViewById(R.id.mycrono)).stop();
}
............. // standard android methods
results crazy numbers...
i am using chronometer to start from last time l3 which is in second
chronometer.setBase(SystemClock.elapsedRealtime()
- (0 * 60000 + l3 * 1000));
chronometer.start();
This is works for me. I have 3 buttons (Start, pause, stop).
private var stopTime : Long = 0
/*Put this in your method, where you want to handle the buttons.
I worked with FloatingActionsButtons*/
fab_start.setOnClickListener {
chronometer.base = SystemClock.elapsedRealtime() + stopTime
chronometer.start()
}
fab_pause.setOnClickListener {
stopTime = chronometer.base - SystemClock.elapsedRealtime()
chronometer.stop()
}
fab_stop.setOnClickListener {
chronometer.base = SystemClock.elapsedRealtime()
stopTime = 0
chronometer.stop()
}
Related
I'm trying to implement a Timer counter, but all that I see is CountDown and I don't want to count down time, I just want start from 00:00 and every second sum one second until 60:00, I've been trying to implement this :
1.-Android timer? How? - Answer
2.- Chronometer
And they didn't help me at all.. can you guide me how to start time from 00:00 and end in 60:00?
Answer here :
As Usama Zafar put his answer, I updated the code to control this CountDownTimer in case you'll need it...
I created
CountDownTimer cdtTimer;
Then the method I have to startTimer() that starts to count the time it's like this :
private void StartTimer(){
final long EndTime = 3600;
cdtTimer = new CountDownTimer(EndTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
long secondUntilFinished = (long) (millisUntilFinished/1000);
long secondsPassed = (EndTime - secondUntilFinished);
long minutesPassed = (long) (secondsPassed/60);
secondsPassed = secondsPassed%60;
tvCounterTimer.setText(String.format("%02d", minutesPassed) + ":" + String.format("%02d", secondsPassed));
}
public void onFinish() {
tvCounterTimer.setText("done!");
}
}.start();
}
Then wherever I want to cancel this CountDownTimer I simply do
cdtTimer.cancel();
The simplest way to implement Timer is to obviously use CountDown as stated on Android's official guide:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
But as per your requirement you don't want to count down rather you wish to count up until you reach 60min mark. How can we do it is indeed an interesting question. You can try implementing a Runnable and get system time in milliseconds on each tick using: System.currentTimeMillis().
It tends to get complex right? So why not play with the CountDown Timer and make it work to our needs? How can we do it? Observe the below code:
long StartTime = 0; //Starting from 00:00
long EndTime = 3600; //End at min:sec converted to seconds
new CountDownTimer(EndTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
long secondUntilFinished = (long) (millisUntilFinished/1000);
long secondsPassed = (EndTime - secondUntilFinished);
long minutesPassed = (long) (secondsPassed/60);
secondsPassed = secondsPassed%60;
// So now at this point your time will be: minutesPassed:secondsPassed
mytextView.setText(String.format("%02d", minutesPassed) + ":" + String.format("%02d", secondsPassed));
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
The code is very easy to understand. If you still have any queries comment them and I will address them. Hope this is helpful.
So i have here Quiz App and have timer. So what i want to happen for example i have set the timer for 15 seconds and if the user answer the question in 5 seconds i want the 10 seconds ramaining become 10 points and it will add to previous score plus the score of you will get upon answering the questions. so for now i have this ...
if(savedInstanceState!=null){
//saved instance state data
int exScore = savedInstanceState.getInt("score");
scoreText.setText("Score: "+exScore);
}
Timer = new CountDownTimer(15000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tv_time.setText("" + millisUntilFinished / 1000);
int progress = (int) (millisUntilFinished / 150);
progressBar.setProgress(progress);
}
#Override
public void onFinish() {
progressBar.setProgress(0);
timeUp(context);
}
}.start();
and here is the one for onclick. if the user answer correctly it will add 10points automatically
public void onClick(View view) {
Button clicked = (Button) view;
int exScore = getScore();
if (clicked.getText().toString().equals(this.active_question.getAnswer()) ) {
if (this.questions.size() > 0) {
setQuestion(questions.poll());
scoreText.setText("Score: " + (exScore + 10))
} else {
CustomGameOver cdd = new CustomGameOver(PlayQuizActivity.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
setHighScore();
Timer.cancel();
}
}
I dont have any idea on how to get the remaianing time on CountdownTimer and add it as a score when the answer is correct. could anyone please help me please.
Just use millisUntilFinished from onTick of the CountDownTimer
And the bonus will be millisUntilFinished/1000
P.S I think you better use a lower interval than 1000, so the ProgressBar will seem smoother.
All you need to do is declare a long variable timeleft in your MainActivity.
long timeleft;
Then, when you create a new Timer, set the "onTick" override to update the timeleft variable each "onTick" (which in the following example is 1000 milliseconds )
timer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}
}
Your app can access then the variable timeleft every time you need to check how much time is left.
score = score + timeleft / 1000; // divide by 1000 to get seconds
Have in mind that if you need to update the timer, you have to cancel it and create a new timer with the updated time left (and the same override);
timeleft = timeleft + bonustime; // (if you want to add bonus time, remember has to be in milliseconds)
if( timer != null){ timer.cancel();} // better check first if the timer exists
timer = new CountDownTimer(timeleft, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}
I'm in the process of designing a chronometer / countdown timer app for Android 2.2 and would like one button press to start both the chronometer and the timer simultaneously. So, ideally, I'd like the seconds (time) on both the chronometer and timer to change at the same instance. (The timer will be counting down even as the chronometer is counting up). Since I'm using the chronometer and timer functionality provided by Android, I wrote the following piece of code when the user presses the 'Start' button
private boolean mStartPressedOnce = false;
long mTimeWhenStopped = 0;
Chronometer mChronometer;
MyCounter mCounter;
...
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
// Perform some initialization for the chronometer depending
// on the button press
if (mStartPressedOnce == false) {
mChronometer.setBase(SystemClock.elapsedRealtime());
} else {
mChronometer.setBase(SystemClock.elapsedRealtime() + mTimeWhenStopped);
}
// Perform the initialization for the timer
mCounter = new MyCount(45000, 1000);
// Fire up the chronometer
mChronometer.start();
// Fire up the timer
mCounter.start();
break;
case R.id.ResetButton:
// Reset the chronometer
mChronometer.setBase(SystemClock.elapsedRealtime());
mTimeWhenStopped = 0;
break;
case case R.id.StopButton:
mStartPressedOnce = true;
// Stop the chronometer
mTimeWhenStopped = mChronometer.getBase() - SystemClock.elapsedRealtime();
mChronometer.stop();
break;
}
...
public class MyCounter extends CountDownTimer {
#Override
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
// Nothing to do here
}
#Override
public void onTick(long millisUntilFinished) {
long seconds = (long) (millisUntilFinished / 1000);
long minutes = (long) ((millisUntilFinished / 1000) / 60);
long hours = (long) (((millisUntilFinished / 1000) / 60) / 60);
// Do some formatting to make seconds, minutes and hours look pretty
// Update the timer TextView
(TextView) findViewById(R.id.CountDownTimerTextView))
.setText(hours + ":" + minutes + ":" + seconds);
}
}
Though it looks like the seconds on the chronometer and timer are in sync initially, after a short time, they seem to go off and the second updates for both occur at different times.
Was wondering what I could do to fix this. I did come across - and read this thread
Running multiple AsyncTasks at the same time -- not possible?
I realize that there may be a design change needed but I'm not sure exactly what needs to be done.
Edit: Included types for chronometer and timer and method for calculating time using Chronometer - per jolivier and njzk2's suggestions
You can retrieve the current time with System.currentTimeMillis(), store it into a variable and forward it to both mChronometer and mCounter, so that they use the same time reference although their task started at different time.
Edit: with the given types, the android documentation about Chronometer will tell you that you can use elapsedRealTime to achieve what I said.
CountDownTimer does not have this and its start method is final so you may want to use another implementation, a better view of your use case might help us.
Basically, wanting two threads to perform an action at the same millisecond is never a good idea, one of them will serve as the clock and the other one must be a slave and listen to the clock.
So, after mulling over this for some time and going off of the suggestion jolivier so generously shared with us, I realized that there exists a method called onChronometerTick which is called every time there is chronometer tick (every second, in this case). So, I thought of subtracting 1000 milliseconds from the counter every time the method is called and update the timer display accordingly. I got rid of the Android timer piece (CountDownTimer) completely. I figured this would be a nice way to have both displays update at the same time. It's also a simple implementation of a timer.
I'm happy to report that it seems to work well. Both the timer and chronometer displays indeed update at the same time. So, the original question looks like it's answered. Unfortunately, I ran into an off-by-two error on the timer front that I fixed with an ugly hack. I'm posting what I have so far. Any suggestions on how to fix the hack or improve the code are welcome. Note that I have commented the code to try to make it easy to understand what's been done.
Edit for bug: One more thing I noticed is that after around 10 minutes or so the chronometer and timer are off by one second. More precisely, the timer is behind the chronometer by one second. Not yet sure why this happens.
private boolean mStartPressedOnce = false;
long mTimeWhenStopped = 0;
Chronometer mChronometer;
long millisUntilFinished = 0;
boolean firstPassOver = false;
int counter = 0;
...
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
// Perform some initialization for the chronometer depending
// on the button press
if (mStartPressedOnce == false) {
mChronometer.setBase(SystemClock.elapsedRealtime());
} else {
mChronometer.setBase(SystemClock.elapsedRealtime() + mTimeWhenStopped);
}
// Fire up the chronometer
mChronometer.start();
break;
case R.id.ResetButton:
// Reset the chronometer
mChronometer.setBase(SystemClock.elapsedRealtime());
mTimeWhenStopped = 0;
break;
case case R.id.StopButton:
mStartPressedOnce = true;
// Stop the chronometer
mTimeWhenStopped = mChronometer.getBase() - SystemClock.elapsedRealtime();
mChronometer.stop();
break;
}
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stop_watch);
mChronometer = (Chronometer) findViewById(R.id.StopWatchTextView);
// Initialize the number of milliseconds before the timer expires (
// set the timer) - in this case to 46 seconds
millisUntilFinished = 46000;
// Display how many seconds remain before the timer expires
((TextView) findViewById(R.id.CountDownTimerTextView)).setText(hours
+ ":" + minutes + ":" + millisUntilFinished / 1000);
// In line with the suggestion provided by jolivier - make the timer
// the slave and update its display every time the chronometer
// ticks
mChronometer
.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
// Update the display for the chronometer
CharSequence text = chronometer.getText();
chronometer.setText(text);
// Update the display for the timer
// !!! BUG !!!
// Looks like onChronometerTick is called at the 0th second
// and this causes an off by two error if a count down timer
// is being implemented. Fixed it with this hack. There's gotta
// be a more elegant solution, though.
if(counter >= 2) {
millisUntilFinished1 = millisUntilFinished1 - 1000;
counter = 2;
}
counter++;
if (millisUntilFinished >= 0) {
long seconds = (long) (millisUntilFinished / 1000);
long minutes = (long) ((millisUntilFinished / 1000) / 60);
long hours = (long) (((millisUntilFinished / 1000) / 60) / 60);
// Do some formatting to make seconds, minutes and hours look pretty
// Update the timer TextView
((TextView) findViewById(R.id.CountDownTimerTextView))
.setText(hours + ":" + minutes + ":"
+ seconds);
}
}
});
// Other code
...
}
I have an app that tells me how many hours to go at school ( :P ). I have a textview with the text Time: ( Hours to go ). This should be 6.2 but it is 6 at the moment, then when I click start it says School finished instantly and then crashes. Oh, I want to show the time in hours, like this ( 6.2 = 6 hours 20 minutes ).
What could be the problem?
Code startActivity:
package com.nieeli.timer;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class startActivity extends Activity implements OnClickListener {
private static final String tag = "Main";
private MalibuCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private Button startB;
private TextView text;
private TextView timeElapsedView;
private final long startTime = 22500000/3600000;
private final long interval = 1/100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
timeElapsedView = (TextView) this.findViewById(R.id.timeElapsed);
countDownTimer = new MalibuCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime));
}
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("Start");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Stop and Reset");
}
}
// CountDownTimer class
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("School Finished!");
timeElapsedView.setText("Time Passed: "
+ String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Left: "
+ String.valueOf(timeElapsed));
}
}
}
Haven't made any changes in manifest or layout.
Thanks :D
First, remember that long is an integer type.
private final long interval = 1/100;
Is not equivalent to 0.01; I believe it would work out to zero. Also, this is how often you want your onTick to be called; I believe you're trying to say you want to be called every 0.01 milliseconds, which seems excessive. Perhaps you meant every 100 milliseconds (ten times a second)?
You may also want to swap the startB.setText lines so that when it is stopped it shows "Start" and when it is started it shows "stopped"
You want to convert milliseconds to hours and minutes? You could try something like this:
long totalMinutes = millis / 1000 / 60;
long hours = millis / 60;
long minutes = totalMinutes - (hours * 60);
EDIT:
There are two main approaches if you want your countdown number (6.2 representing 6 hours and 20 minutes) to decrease by .1 every ten minutes.
The first option is to set "interval" to 10 * 60 * 1000 (the number of milliseconds in ten minutes). Then in onTick, take a float number (10.0 or whatever) and decrease by 0.1. That may be a quick and dirty method, if it even works, but it's not ideal.
The second is to do what I had described above. Then when you have the number of hours and number of minutes:
float timeRemaining = (float) hours + (float) minutes / 100
use String.format to display it in the textview. Something like
String.format("%.1f%n", timeRemaining)
to show it with only one decimal point.
I didn't actually try the code--but off the top of my head, this should give you some tips to steer you in the right direction.
I am trying to completely restart Chronometer and its does not work. Instead it is being paused. Basically what I am trying to do is to do something while chronometer is counting till 10. After its done we prompt the user to try again. In which case we want to redo the count from 1 to 10 sec. But the Chronometer starts from the paused time instead of starting 0.
here is the code:
_cutOfTime = 10; // constant
every time button is pressed do startRecording()
it should always initiate the Chronometer instead of stop/pause it, but it does the opposite
protected void startRecording(){
this._watch = (Chronometer) findViewById(R.id.chrono);
if (this._watch != null)
this._watch.setOnChronometerTickListener(new OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long countUp = (SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000;
Log.i(_tag, "time now: " + String.valueOf(countUp));
if(countUp > _cutOfTime)
{
Log.i(_tag, "stop recording!!: ");
_watch.stop();
stopRecordWav();
launchPromptWithResults();
}
long sec = countUp % 60;
String asText = "" + sec;
_textView.setText("Recorded: " + asText);
}
});
if (_watch != null)
_watch.start();
}
Is there a way to reset the chronometer so it does not pause but completely stop?
When I played with the chronometer awhile back I just used the setBase() method to set the base to the current time just before calling start(). Depending on your exact needs you may need to add some logic around whether to reset the chronometer or not before starting it.
View.OnClickListener mStartButtonListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
}
};