void startResendTimer(){
resendOtpTextView.setEnabled(false);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
timeoutSeconds--;
resendOtpTextView.setText("Resend OTP in "+timeoutSeconds +" seconds");
if(timeoutSeconds<=0){
timeoutSeconds =60L;
timer.cancel();
runOnUiThread(() -> {
resendOtpTextView.setEnabled(true);
});
}
}
},0,1000);
}
当我使用
scheduleAtFixedRate
时,整个代码块都会被划掉。当我使用schedule
时,我想要的事件不会发生。为什么?
1000 毫秒(1 秒)是一个非常短的时间。确保您的代码块始终在那 1 秒内可执行。
schedule
应该只执行代码块一次。因此,如果块执行失败,则没有第二次执行机会。
尝试使用 android CountDownTimer 以下是一个示例。
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
// logic to set the EditText could go here
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
这是官方文档的链接: https://developer.android.com/reference/android/os/CountDownTimer