Schedule a countdown until a time in the future, with regular notifications on intervals along the way.We can start countdown by using creating own Thread or By using CountDownTimer class of android.os package.
Here an example of showing a 1-second countdown in The text fields by the Thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
public void countDownStart(final String endingDate) { linearLayout1 = (LinearLayout) findViewById(R.id.ll1); linearLayout2 = (LinearLayout) findViewById(R.id.ll2); tvDay = (TextView) findViewById(R.id.txtTimerDay); tvHour = (TextView) findViewById(R.id.txtTimerHour); tvMinute = (TextView) findViewById(R.id.txtTimerMinute); tvSecond = (TextView) findViewById(R.id.txtTimerSecond); tvEvent = (TextView) findViewById(R.id.tvevent); handler = new Handler(); runnable = new Runnable() { @Override public void run() { handler.postDelayed(this, 1000); try { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); // Here Set your Event Date Date eventDate = dateFormat.parse(endingDate); Date currentDate = new Date(); if (!currentDate.after(eventDate)) { long diff = eventDate.getTime() - currentDate.getTime(); long days = diff / (24 * 60 * 60 * 1000); diff -= days * (24 * 60 * 60 * 1000); long hours = diff / (60 * 60 * 1000); diff -= hours * (60 * 60 * 1000); long minutes = diff / (60 * 1000); diff -= minutes * (60 * 1000); long seconds = diff / 1000; tvDay.setText("" + String.format("%02d", days)); tvHour.setText("" + String.format("%02d", hours)); tvMinute.setText("" + String.format("%02d", minutes)); tvSecond.setText("" + String.format("%02d", seconds)); } else { linearLayout1.setVisibility(View.VISIBLE); linearLayout2.setVisibility(View.GONE); tvEvent.setText("Android Event Start"); handler.removeCallbacks(runnable); // handler.removeMessages(0); } } catch (Exception e) { e.printStackTrace(); } } }; handler.postDelayed(runnable, 0); } |
Where Handler is android.os package class.
Ref. http://stackoverflow.com/questions/10032003/how-to-make-a-countdown-timer-in-android