¿Cómo hacer un temporizador de cuenta regresiva en Android?

Tengo dos EditTexts en XML. En un EditText, el usuario puede poner un número como minutos y en otro EditText, un número como segundos. Después de hacer clic en el botón de finalizar, los segundos EditText deberían comenzar a contar atrás y actualizar su texto cada segundo.

Además, ¿cómo puedo mantenerlo actualizado hasta que llegue a cero minutos y cero segundos?

new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); //here you can have your logic to set text to edittext } public void onFinish() { mTextField.setText("done!"); } }.start(); 

Consulte este enlace .

si usa el siguiente código (como se menciona en la respuesta aceptada),

 new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); //here you can have your logic to set text to edittext } public void onFinish() { mTextField.setText("done!"); } }.start(); 

Dará como resultado la pérdida de memoria de la instancia de la actividad donde utiliza este código, si no limpia cuidadosamente las referencias.

usa el siguiente código

 //Declare timer CountDownTimer cTimer = null; //start timer function void startTimer() { cTimer = new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { } }; cTimer.start(); } //cancel timer void cancelTimer() { if(cTimer!=null) cTimer.cancel(); } 

Debe llamar a cTtimer.cancel () siempre que se llame a onDestroy () / onDestroyView () en la Actividad / Fragmento propietario.

solo copie y pegue el siguiente código ……..

Actividad principal

paquete com.example.countdowntimer;

 import java.util.concurrent.TimeUnit; import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.widget.TextView; public class MainActivity extends Activity { TextView text1; private static final String FORMAT = "%02d:%02d:%02d"; int seconds , minutes; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text1=(TextView)findViewById(R.id.textView1); new CountDownTimer(16069000, 1000) { // adjust the milli seconds here public void onTick(long millisUntilFinished) { text1.setText(""+String.format(FORMAT, TimeUnit.MILLISECONDS.toHours(millisUntilFinished), TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes( TimeUnit.MILLISECONDS.toHours(millisUntilFinished)), TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)))); } public void onFinish() { text1.setText("done!"); } }.start(); } } 

activity_main.xml

     

enter image description here

MainActivity.java

 package com.zeustechnocrats.countdown; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { private String EVENT_DATE_TIME = "2018-12-31 10:30:00"; private String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private LinearLayout linear_layout_1, linear_layout_2; private TextView tv_days, tv_hour, tv_minute, tv_second; private Handler handler = new Handler(); private Runnable runnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.count_down); initUI(); countDownStart(); } private void initUI() { linear_layout_1 = findViewById(R.id.linear_layout_1); linear_layout_2 = findViewById(R.id.linear_layout_2); tv_days = findViewById(R.id.tv_days); tv_hour = findViewById(R.id.tv_hour); tv_minute = findViewById(R.id.tv_minute); tv_second = findViewById(R.id.tv_second); } private void countDownStart() { runnable = new Runnable() { @Override public void run() { try { handler.postDelayed(this, 1000); SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); Date event_date = dateFormat.parse(EVENT_DATE_TIME); Date current_date = new Date(); if (!current_date.after(event_date)) { long diff = event_date.getTime() - current_date.getTime(); long Days = diff / (24 * 60 * 60 * 1000); long Hours = diff / (60 * 60 * 1000) % 24; long Minutes = diff / (60 * 1000) % 60; long Seconds = diff / 1000 % 60; // tv_days.setText(String.format("%02d", Days)); tv_hour.setText(String.format("%02d", Hours)); tv_minute.setText(String.format("%02d", Minutes)); tv_second.setText(String.format("%02d", Seconds)); } else { linear_layout_1.setVisibility(View.VISIBLE); linear_layout_2.setVisibility(View.GONE); handler.removeCallbacks(runnable); } } catch (Exception e) { e.printStackTrace(); } } }; handler.postDelayed(runnable, 0); } protected void onStop() { super.onStop(); handler.removeCallbacks(runnable); } } 

activity_main.xml

                         

Simplemente llame a la función siguiente pasando los segundos y el objeto textview

 public void reverseTimer(int Seconds,final TextView tv){ new CountDownTimer(Seconds* 1000+1000, 1000) { public void onTick(long millisUntilFinished) { int seconds = (int) (millisUntilFinished / 1000); int minutes = seconds / 60; seconds = seconds % 60; tv.setText("TIME : " + String.format("%02d", minutes) + ":" + String.format("%02d", seconds)); } public void onFinish() { tv.setText("Completed"); } }.start(); } 

Revers temporizador CountDown con horas minutos y segundos

 public void reverseTimer(int Seconds, final TextView tv) { new CountDownTimer(Seconds * 1000 + 1000, 1000) { public void onTick(long millisUntilFinished) { int seconds = (int) (millisUntilFinished / 1000); int hours = seconds / (60 * 60); int tempMint = (seconds - (hours * 60 * 60)); int minutes = tempMint / 60; seconds = tempMint - (minutes * 60); tv.setText("TIME : " + String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds)); } public void onFinish() { tv.setText("Completed"); } }.start(); } 

Pruebe de esta manera:

 private void startTimer() { startTimer = new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))); Log.e(TAG, "onTick: "+sec ); tv_timer.setText(String.format("( %02d SEC )", sec)); if(sec == 1) { new Handler().postDelayed(new Runnable() { @Override public void run() { tv_timer.setText("( 00 SEC )"); } }, 1000); } } public void onFinish() { tv_timer.setText("Timer finish"); } }.start(); } 

Usando Kotlin:

 var timer = object: CountDownTimer(30000, 1000) { override fun onTick(millisUntilFinished: Long) { tvTimer.setText("seconds remaining: " + millisUntilFinished / 1000) } override fun onFinish() { tvTimer.setText("done!") } } timer.start() 

La forma de interfaz.

 import android.os.CountDownTimer; /** * Created by saikiran on 07-03-2016. */ public class CountDownTimerCustom extends CountDownTimer { private TimeTickListener mTickListener; private TimeFinishListener mFinishListener; private long millisUntilFinished; public CountDownTimerCustom(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } public void updateTickAndFinishListener(TimeTickListener tickListener) { mTickListener = tickListener; } public void updateFinishListner(TimeFinishListener listener) { mFinishListener = listener; } public long getCurrentMs() { return millisUntilFinished; } public int getCurrentSec() { return (int) millisUntilFinished / 1000; } @Override public void onTick(long millisUntilFinished) { this.millisUntilFinished = millisUntilFinished; if (mTickListener != null) mTickListener.onTick(millisUntilFinished); } @Override public void onFinish() { if (mTickListener != null) mTickListener.onFinished(); mFinishListener.onFinished(); } public interface TimeTickListener { void onTick(long mMillisUntilFinished); void onFinished(); } public interface TimeFinishListener { void onFinished(); } }