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()
Related
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
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 an app that has a timer. I want to put a log in the logcat when 10 seconds are up. The timer does a different task at 20 seconds. Here is my attempt:
Here is the code:
public class TwentySeconds extends Service {
MediaPlayer mp;
final String TAG = "MyCountdown";
CountDownTimer cdt;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "In start command");
cdt = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long timeRemaining = 20000 - millisUntilFinished;
if(timeRemaining % 1000 == 0){
Log.v(TAG, "Time remaining" +(timeRemaining % 1000) + " seconds left");
}
}
#Override
public void onFinish() {
Log.v(TAG, "Finished");
Intent intent = new Intent(TwentySeconds.this,GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.v(TAG, "About to start activity");
startActivity(intent);
}
};
cdt.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
The logic for the code seems great, but for some reason, it is not displaying. Thanks so much for all of your time, please let me know.
{Rich}
CountDownTimer is not a 100% precise timer, so you shouldn't attempt to do such a precise calculation, because it will fail 99% of the time.
Maybe just do:
millisUntilFinished / 1000
as your interval is 1 second.
Try this:
#Override
public void onTick(long millisUntilFinished) {
long timeRemaining = 20000 - millisUntilFinished;
Log.v(TAG, "Time remaining " + (timeRemaining / 1000) + " seconds left");
}
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 have a CountDownTimer in my app setup like this:
new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
clock.setText("Seconds Remaining: " + millisUntilFinished / 1000);
secsrem = (int) millisUntilFinished / 1000;
}
public void onFinish() {
//...}
}.start();
I need to access the onFinish method in another method in my app so that when a button is pressed it will call the timers onFinish method. How would i do this?
Just store your timer in a variable:
public class YourClass {
public CountDownTimer timer = null;
...
timer = new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
clock.setText("Seconds Remaining: " + millisUntilFinished / 1000);
secsrem = (int) millisUntilFinished / 1000;
}
public void onFinish() {
//...}
}
timer.start();
...
Then you can do:
timer.onFinish();
Btw, I think you should not call onFinish yourself, it will be called by system when the time is up. If you want to cancel the timer instead use:
timer.cancel();