Android基于Handler实现倒计时

  1. 全局变量
    int hou = 1;
    int min = 59;
    int sec = 60;
    Handler mhandler = new Handler();
  1. 开启倒计时
	time1.setText("02 : 00 : 00");
    mhandler.postDelayed(runnable, 1000);
    hou = 1;
    min = 59;
    sec = 60;
  1. 倒计时线程
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (hou == 0) {
                Toast.makeText(MainActivity.this, "时间到", Toast.LENGTH_SHORT);
            }
            if (sec > 0) {
                sec--;
            } else {
                sec = 59;
                if (min == 0) {
                    min = 59;
                    hou--;
                } else{
                    min--;
                }
            }
            String hour, minute, second;
            hour = (hou < 10) ? "0"+hou : ""+hou;
            minute = (min < 10) ? "0"+min : ""+min;
            second = (sec < 10) ? "0"+sec : ""+sec;
            time1.setText(hour +" : "+ minute +" : "+ second);
            mhandler.postDelayed(this, 1000);
        }
    };

你可能感兴趣的:(Android)