简单使用CountDownTimer

/*CountDownTimer的内部实现是采用Handler机制,
通过sendMessageDelayed延迟发送一条message到主线程的looper中,
然后在自身中收到之后判断剩余时间,并发出相关回调,然后再次发出message的方式。*/

public class MainActivity extends AppCompatActivity {
    private Button timeBt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timeBt = (Button) findViewById(R.id.time_bt);
        timeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timer.start();
                timeBt.setEnabled(false);
            }
        });
    }

    /*CountDownTimer (long millisInFuture, long countDownInterval)
  参数1,设置倒计时的总时间(毫秒)
  参数2,设置每次减去多少毫秒
  +1000是为了0秒显示,+50是为了减少耗时*/
    private CountDownTimer timer = new CountDownTimer(9000 + 1050, 1000) {
        @Override
        public void onTick(long l) {
            timeBt.setText((l / 1000) - 1 + "秒后可重发");
        }

        @Override
        public void onFinish() {
            if (!MainActivity.this.isFinishing()) {//避免内存泄漏
                timeBt.setEnabled(true);
                timeBt.setText("获取验证码");
            }

        }
    };

    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }
}

猜你喜欢

转载自blog.csdn.net/Ivor_Chan/article/details/80393116
今日推荐