Picture Reference
I need help adding one more minute using the on click button in Android Studio
Here's some of my timer code:
private void startTimer() {
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
mTimerRunning = false;
btnTest.setText("Start");
}
}.start();
mTimerRunning = true;
btnTest.setText("Pause");
}
private void pauseTimer() {
mCountDownTimer.cancel();
mTimerRunning = false;
btnTest.setText("Start");
}
private void updateCountDownText() {
int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewShowTime.setText(timeLeftFormatted);
mProgressBar.setProgress((int)(mTimeLeftInMillis / 1000));
}
Unfortunately, this class does not have such a feature.
you can save the count of the button click, then create a new CountDownTimer with the timeout that you want. and you need to consider the remaining time in the onTick method.
You can create CustomCountDowntimer that extends from CountDownTimer. And do the things described above there.
see this link
Related
Here I have made this method for starting my timer and the one below it updates the timer:
private void startTimer()
{
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
progress++;
pb.setProgress((int)progress*100/((int)millisUntilFinished/1000));
}
#Override
public void onFinish()
{
progress++;
pb.setProgress(100);
//Vibration
if (Build.VERSION.SDK_INT >= 26)
{
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(MainActivity2.this,"Done",Toast.LENGTH_SHORT).show();
}
else
{
((Vibrator) getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createWaveform(new long[]{150}, new int[]{VibrationEffect.EFFECT_CLICK},-1));
}
}
}.start();
}
private void updateCountDownText()
{
//time in minutes and seconds
int minutes = (int)(mTimeLeftInMillis/1000)/60;
int seconds = (int)(mTimeLeftInMillis/1000)%60;
//formating the above to appear as String
String timeLeftFormatted = String.format("%02d:%02d",minutes,seconds);
timer.setText(timeLeftFormatted);
}
"pb" is the name of my progressbar. It keeps finishing earlier than the countdown by 2 minutes and I don't know how to synchronize them. Also upon completion the vibration is not triggered for some reason even though it did before. "progress" is initialized as zero as a global variable.
Here is the solution:
long millisInFuture;
private void startTimer() {
millisInFuture = mTimeLeftInMillis;
mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updateCountDownText();
long millisPassed = millisInFuture - mTimeLeftInMillis;
progress = (int) (millisPassed * 100 / millisInFuture);
pb.setProgress(progress);
}
#Override
public void onFinish() {
pb.setProgress(100);
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
VibrationEffect effect =
VibrationEffect.createOneShot(150, VibrationEffect.DEFAULT_AMPLITUDE);
vibrator.vibrate(effect);
Toast.makeText(MainActivity2.this, "Done", Toast.LENGTH_SHORT).show();
} else {
vibrator.vibrate(150);
}
}
}.start();
}
But I don't see when you initialize your progressbar.
If you set pb.max ( or setMax in Java ) = 100
And on each onTick call a method :
private changePb(long millisUntilFinished){
pb.progress = (millisUntilFinished / millisStartValue) * 100
}
Where millisStartValue was the first value you put in new CountDownTimer(mTimeLeftInMillis
And in onFinish, you don't have to put new value for progressbar.
I am making a chess clock but in it I need a delay (Like it waits 10 seconds before counting). I used a Handler for it but if the button is clicked in the 10 seconds, nothing happens. Please help! Thanks!
My code:
mHandler.postDelayed(new Runnable() {
public void run() {
// count down timer start
timer2 = new CountDownTimer(totalSeconds, Integer.parseInt(delay.getText().toString())) {
public void onTick(long millisUntilFinished) {
secondsTimer = (int) (millisUntilFinished / 1000) % 60;
minutesTimer = (int) ((millisUntilFinished / (1000 * 60)) % 60);
hoursTimer = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
person2.setText(hoursTimer + ":" + minutesTimer + ":" + secondsTimer);
}
public void onFinish() {
person2.setText("Time Up!");
person2.setBackgroundColor(Color.RED);
mp.start();
}
}.start();
}
}, finalDelay);
I want a delay but I don't want to lock the UI and make the app unresponsive as it is doing right now with the handler. Any help will be appreciated! Thanks in advance!
I think you shouldn't put CountdownTimer into Handler. You could create 2 handler instead. Here is an example.
private void startHandlerAndWait10Seconds(){
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
public void run() {
// Start Countdown timer after wait for 10 seconds
startCountDown();
}
}, 10000);
}
private void startCountDown {
final Handler handler2 = new Handler();
handler2.post(new Runnable() {
int seconds = 60;
public void run() {
seconds--;
mhello.setText("" + seconds);
if (seconds < 0) {
// DO SOMETHING WHEN TIMES UP
stopTimer = true;
}
if(stopTimer == false) {
handler2.postDelayed(this, 1000);
}
}
});
}
If you want to start the timer immediately,
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Handler().post(new Runnable() {
public void run() {
// count down timer start
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished));
}
public void onFinish() {
button.setText("Time Up!");
}
}.start();
}
});
}
});
And if you want to execute it after a certain time period, then
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Handler().postDelayed(new Runnable() {
public void run() {
// count down timer start
new CountDownTimer(100000, 1000) {
public void onTick(long millisUntilFinished) {
button.setText(String.valueOf(millisUntilFinished));
}
public void onFinish() {
button.setText("Time Up!");
}
}.start();
}
}, 1000);
}
});
You can avoid using Handler starting timer immediately
private fun start10SecondsDelayTimer() {
var delayCount = 10
val timer = object : CountDownTimer(1_000_000L, 1000L) {
override fun onTick(millisUntilFinished: Long) {
if (delayCount > 0) {
delayCount--
} else {
//your calculations
}
}
override fun onFinish() {
//some calculations
}
}
timer.start()
}
but first ticks will be without your calculations
i have a textview that has a int number of seconds to count down from all the way to 0. i pass in a random number selected by a user to the timer and it counts down to 0. so i pass the variable S into timer
my textview:
mSeconds = (TextView)findViewById(R.id.secondsLabel);
my timer:
int s = //int taken from on spinner in another class
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
finish();
}
}, s * 1000);
new CountDownTimer(s, 1000) {
public void onTick(long millisUntilFinished) {
mSeconds.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
}
};
my textview does not display anything at all? how can i get it to show the seconds counting down?
You are not starting the CountDownTimer.
Do this
new CountDownTimer(s, 1000) {
public void onTick(long millisUntilFinished) {
mSeconds.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
}
}.start();
Start your count down timer
CountDownTimer ct = new CountDownTimer(s, 1000) {
public void onTick(long millisUntilFinished) {
mSeconds.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
}
};
ct.start();
You should manage it on UI thread
I am new to Android Development and trying to make little Game.
CountDownTimer.cancel() is not working for me.
Any Idea?
Thank Your for your Answer!
CountDownTimer cdt = new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
maxTime = (int) (millisUntilFinished / 1000);
timer.setText(String.valueOf(maxTime));
}
public void onFinish() {
}
};
if (startTimer == true) {
cdt.start();
} else {
cdt.cancel();
}
I have to do an assumption right here because the code doesn't show much! apparently you are using the countDownTimer inside your onCreate as an inner class so that will trigger the timer when startTimer == true and it would create the object no matter what! I guess it would be better to create a global instance of CountDownTimer.
And write your code in this way:
if(startTimer == true) {
cdt = new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
maxTime = (int) (millisUntilFinished / 1000);
timer.setText(String.valueOf(maxTime));
}
public void onFinish() {
}
}.start(); //start the countdowntimer
}
else{
cdt.cancel();
}
Boolean Myboolean = true;
CountDownTimer MyCountDownTimer = new CountDownTimer(10000, 1000)
{
#Override
public void onFinish()
{
}
#Override
public void onTick(long millisUntilFinished)
{
Log.i("onTick" , String.valueOf((millisUntilFinished / 1000) % 60));
if(!Myboolean ) { cancel(); }
}
}.start();
i had this issue , the CountDownTimer will not cancle with (MyCountDownTimer.cancel();) , the best way is to use Boolean , set the Boolean to false to cancel the CountDownTimer. in any place you want (Myboolean =false;)
It's a countdown timer and i want to print in minutes and seconds. ex(300000mili)5 minutes, and count 4:60, 4:59...
here is part of my code
final MyCounter timer = new MyCounter(300000,1000);
blue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.start();
}
});
}
public class MyCounter extends CountDownTimer {
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
blue.setText("Live");
}
#Override
public void onTick(long millisUntilFinished) {
blue.setText((millisUntilFinished/60000)+":"+(millisUntilFinished/5000));
// i tried this
}
}
And how can i put to vibrate when missing 20 seconds? and when it finished?
thanks and sorry for my bad english
http://developer.android.com/reference/android/os/CountDownTimer.html
TextView _tv = (TextView) findViewById( R.id.textView1 );
new CountDownTimer(30000, 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished) {
_tv.setText(""+String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
_tv.setText("done!");
}
}.start();
Since java 1.5 there is the java.util.concurrent.TimeUnit class
_tv.setText(""+String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html
A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.
For Java versions below 1.5 or for systems that do not fully support the TimeUnit class the following equations can be used:
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
To vibrate
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
<uses-permission android:name="android.permission.VIBRATE"/> // permission in manifest
Edit:
Vibrate at 4 min 55 seconds for 500 milli seconds
if((TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished)==4) &&
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))==55)
{
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
}
Just use the modulo operator % to get the remaining milliseconds and divide by 1000 to convert to seconds.
blue.setText((millisUntilFinished / 60000)+":"+(millisUntilFinished % 60000 / 1000));
mCountDownTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTextViewAdTime.setText("Ad: " + String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
mTextViewAdTime.setText("Ad:");
}
}.start();
Kotlin version of Ashwin's answer:
var mCountDownTimer = object : CountDownTimer(duration, 1000) {
override fun onTick(millisUntilFinished: Long) {
val text = "OTP is valid for ${String.format(
"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(
millisUntilFinished
)
))} minutes. Please enter the OTP "
binding.timer.text = text
}
override fun onFinish() {
binding.timer.text = "Request OTP again to proceed."
}
}.start()