2012-08-09 16 views
6

Estoy tratando de hacer un temporizador de cuenta atrás para un juego/fecha en android. Quiero crear un temporizador que muestre los días, las horas, los minutos y los segundos en una fecha que especifique con una variable final. El temporizador configura las vistas de texto para mostrar los días, horas, minutos y segundos al usuario.Android Countdown Timer to Date

¿Alguna sugerencia acerca de cómo podría codificar esto?

+0

http://joda-time.sourceforge.net/faq.html#datediff – iTurki

Respuesta

5

Aquí está incorporado countDownTimer que mostrará la hora con formato de sus días, horas, minutos un Android, y segundos todos en una TextView:

public class Example extends Activity { 
    CountDownTimer mCountDownTimer; 
    long mInitialTime = DateUtils.DAY_IN_MILLIS * 2 + 
         DateUtils.HOUR_IN_MILLIS * 9 + 
         DateUtils.MINUTE_IN_MILLIS * 3 + 
         DateUtils.SECOND_IN_MILLIS * 42; 
    TextView mTextView; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mTextView = (TextView) findViewById(R.id.empty); 

     mCountDownTimer = new CountDownTimer(mInitialTime, 1000) { 
      StringBuilder time = new StringBuilder(); 
      @Override 
      public void onFinish() { 
       mTextView.setText(DateUtils.formatElapsedTime(0)); 
       //mTextView.setText("Times Up!"); 
      } 

      @Override 
      public void onTick(long millisUntilFinished) { 
       time.setLength(0); 
       // Use days if appropriate 
       if(millisUntilFinished > DateUtils.DAY_IN_MILLIS) { 
        long count = millisUntilFinished/DateUtils.DAY_IN_MILLIS; 
        if(count > 1) 
         time.append(count).append(" days "); 
        else 
         time.append(count).append(" day "); 

        millisUntilFinished %= DateUtils.DAY_IN_MILLIS; 
       } 

       time.append(DateUtils.formatElapsedTime(Math.round(millisUntilFinished/1000d))); 
       mTextView.setText(time.toString()); 
      } 
     }.start(); 
    } 
} 
+0

número de días es siempre 1 puede eso ser disminuido? –

+0

@AbhayKumar Actualicé mi código y le di una etiqueta a los días. – Sam

+0

Este método se salta hasta 3 segundos por minuto en mi emulador. No lo está haciendo en mi teléfono. ¿Es eso un problema de emulador, o debería esperar que eso suceda en otros teléfonos ?. –

12

countDownTimer que mostrará la hora con formato de horas, minutos, días y segundos.

public class DemotimerActivity extends Activity { 
     /** Called when the activity is first created. */ 
     TextView tv; 
     long diff; 
     long milliseconds; 
     long endTime; 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      tv = new TextView(this); 
      this.setContentView(tv); 
      SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm"); 
      formatter.setLenient(false); 


      String oldTime = "21.10.2013, 12:00"; 
      Date oldDate; 
      try { 
       oldDate = formatter.parse(oldTime); 
       milliseconds = oldDate.getTime(); 

       //long startTime = System.currentTimeMillis(); 
       // do your work... 
       long endTime=System.currentTimeMillis(); 

       diff = endTime-milliseconds;  

       Log.e("day", "miliday"+diff); 
       long seconds = (long) (diff/1000) % 60 ; 
       Log.e("secnd", "miliday"+seconds); 
       long minutes = (long) ((diff/(1000*60)) % 60); 
       Log.e("minute", "miliday"+minutes); 
       long hours = (long) ((diff/(1000*60*60)) % 24); 
       Log.e("hour", "miliday"+hours); 
       long days = (int)((diff/(1000*60*60*24)) % 365); 
       Log.e("days", "miliday"+days); 
      } catch (ParseException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      Long serverUptimeSeconds = (System.currentTimeMillis() - milliseconds)/1000; 


       String serverUptimeText = String.format("%d days %d hours %d minutes %d seconds", 
       serverUptimeSeconds/86400, 
       (serverUptimeSeconds % 86400)/3600 , 
       ((serverUptimeSeconds % 86400) % 3600)/60, 
       ((serverUptimeSeconds % 86400) % 3600) % 60 
       ); 


      Log.v("jjj", "miliday"+serverUptimeText); 
      MyCount counter = new MyCount(milliseconds,1000); 
      counter.start(); 


     } 


     // countdowntimer is an abstract class, so extend it and fill in methods 
     public class MyCount extends CountDownTimer { 
      public MyCount(long millisInFuture, long countDownInterval) { 
       super(millisInFuture, countDownInterval); 
      } 

      @Override 
      public void onFinish() { 
       tv.setText("done!"); 
      } 

      @Override 
      public void onTick(long millisUntilFinished) { 
       //tv.setText("Left: " + millisUntilFinished/1000); 

       long diff = endTime - millisUntilFinished; 
       Log.e("left", "miliday"+diff); 
       long seconds = (long) (diff/1000) % 60 ; 
       //Log.e("secnd", "miliday"+seconds); 
       long minutes = (long) ((diff/(1000*60)) % 60); 
       //Log.e("minute", "miliday"+minutes); 
       long hours = (long) ((diff/(1000*60*60)) % 24); 
       //Log.e("hour", "miliday"+hours); 
       int days = (int)((diff/(1000*60*60*24)) % 365); 
       Log.v("days", "miliday"+days); 


       Long serverUptimeSeconds = 
         (System.currentTimeMillis() - millisUntilFinished)/1000; 


        String serverUptimeText = 
        String.format("%d days %d hours %d minutes %d seconds", 
        serverUptimeSeconds/86400, 
        (serverUptimeSeconds % 86400)/3600 , 
        ((serverUptimeSeconds % 86400) % 3600)/60, 
        ((serverUptimeSeconds % 86400) % 3600) % 60 
        ); 

        Log.v("new its", "miliday"+serverUptimeText); 

       // tv.setText(days +":"+hours+":"+minutes + ":" + seconds); 

        tv.setText(serverUptimeText); 
      } 
     } 
    } 
+0

realmente aumenta el contador de tiempo no el contador descendente. – CoDe

3

Intente éste:

SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss"); 
     formatter.setLenient(false); 


     String endTime = "25.06.2017, 15:05:36" 

     Date endDate; 
     try { 
      endDate = formatter.parse(endTime); 
      milliseconds = endDate.getTime(); 

     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     startTime = System.currentTimeMillis(); 

     diff = milliseconds - startTime; 


      mCountDownTimer = new CountDownTimer(milliseconds, 1000) { 
      @Override 
      public void onTick(long millisUntilFinished) { 

       startTime=startTime-1; 
       Long serverUptimeSeconds = 
         (millisUntilFinished - startTime)/1000; 

       String daysLeft = String.format("%d", serverUptimeSeconds/86400); 
       txtViewDays.setText(daysLeft); 

       String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400)/3600); 
       txtViewHours.setText(hoursLeft); 

       String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600)/60); 

       txtViewMinutes.setText(minutesLeft); 

       String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60); 
       txtViewSecond.setText(secondsLeft); 


      } 

      @Override 
      public void onFinish() { 

      } 
     }.start(); 

    } 
+0

esto debe ser aceptado – Dhiru

+0

@Dhiru Estoy de acuerdo. Este funciona –

0

long startTime;

private void start_countdown_timer() 
{ 
    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss"); 
    formatter.setLenient(false); 


    String endTime = "18.09.2017, 15:05:36"; 
    long milliseconds=0; 

    final CountDownTimer mCountDownTimer; 

    Date endDate; 
    try { 
     endDate = formatter.parse(endTime); 
     milliseconds = endDate.getTime(); 

    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    startTime = System.currentTimeMillis(); 


    mCountDownTimer = new CountDownTimer(milliseconds, 1000) { 
     @Override 
     public void onTick(long millisUntilFinished) { 

      startTime=startTime-1; 
      Long serverUptimeSeconds = 
        (millisUntilFinished - startTime)/1000; 

      String daysLeft = String.format("%d", serverUptimeSeconds/86400); 
      //txtViewDays.setText(daysLeft); 
      Log.d("daysLeft",daysLeft); 

      String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400)/3600); 
      //txtViewHours.setText(hoursLeft); 
      Log.d("hoursLeft",hoursLeft); 

      String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600)/60); 
      //txtViewMinutes.setText(minutesLeft); 
      Log.d("minutesLeft",minutesLeft); 

      String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60); 
      //txtViewSecond.setText(secondsLeft); 
      Log.d("secondsLeft",secondsLeft); 


     } 

     @Override 
     public void onFinish() { 

     } 
    }.start(); 


}