import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* 倒计时器:https://developer.android.com/reference/android/os/CountDownTimer
*/
public class MainActivity extends AppCompatActivity {
// 发送短信按钮
private Button btnSend;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = findViewById(R.id.btn_send);
btnSend.setText("发送验证码");
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCountDownTimer != null) {
// 设置按钮不可点击
btnSend.setEnabled(false);
// 开始倒计时
mCountDownTimer.start();
}
}
});
}
/**
* 倒计时(案例:发送验证码,一分钟倒计时)
* 构造函数 CountDownTimer(long millisInFuture, long countDownInterval)
* 第一个参数 millisInFuture: 总的时间(单位:毫秒),从调用到start()倒计时完成并将onFinish() 被调用的未来毫秒数。
* 第二个参数 countDownInterval:间隔时间(单位:毫秒),沿途接收回调的间隔 。 onTick(long)
*/
private CountDownTimer mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
@Override
public void onTick(long l) {
// 定期间隔触发回调
if (btnSend != null) {
btnSend.setText("剩余" + (l / 1000L) + "秒");
}
}
@Override
public void onFinish() {
if (btnSend != null) {
// 倒计时结束
btnSend.setText("重新发送验证码");
// 设置按钮允许点击
btnSend.setEnabled(true);
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (mCountDownTimer != null) {
// 取消倒计时
mCountDownTimer.cancel();
mCountDownTimer = null;
}
btnSend = null;
}
}