我正在进行的项目是每个问题都带有计时器的测验。持续30秒。我注意到如果你在计时器用完之前完成测试,计时器就不会停止运行。因此,如果您接着进行另一项测试,则您尚未完成测试的通知将弹出并覆盖当前活动。我尝试使用cancel()方法,但我确定我放错了地方。
以下是MyCountDownTimer类的片段
public MyCountDownTimer(TextView textCounter, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
@Override
public void onTick(long millisUntilFinished) {
textCounter.setText(String.valueOf(millisUntilFinished / 1000));
}
@Override
public void onFinish() {
Intent retryIntent = new Intent(textCounter.getContext(), Retry.class);
if (textCounter.getContext() instanceof Test1){
whichTest = 1;
retryIntent.putExtra("whichTest",whichTest);
}
textCounter.getContext().startActivity(retryIntent);
}
这是实现方法
的Activity的片段@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_page);
textCounter = ((TextView)findViewById(R.id.textCounter));
myCountDownTimer = new MyCountDownTimer(textCounter, 29000, 1000);
myCountDownTimer.start();
textCounter.setText("");
myCountDownTimer.onTick(29000);
}@Override
public void onClick(View v) {
if (questionIndex == questions7.length){
myCountDownTimer.cancel();
Intent intent1 = new Intent(Test1.this, UsersAnswers1.class);
intent1.putExtra("usersAnswers1", usersAnswers1);
intent1.putExtra("isATOF1", isATOF1);
intent1.putExtra("score1S", score1S);
startActivity(intent1);
}
}
答案 0 :(得分:1)
覆盖活动的onStop方法并使用
等代码@Override
protected void onStop() {
myCountDownTimer.cancel();
super.onStop();
}
因此,只要您的活动进入后台,它就会取消与当前活动相关的任何计时器。