当 activity 不是当前的 activity 时,如何让 MyCountDownTimer 退出?

How can I tell MyCountDownTimer to quit when the activity is not the current activity?

我正在做的项目是一个测验,每个问题都有一个计时器。持续 30 秒。我注意到如果您在计时器用完之前完成测试,计时器不会停止 运行。因此,如果您继续进行另一项测试,您尚未完成测试的通知将弹出并覆盖当前的 activity。我尝试使用 cancel() 方法,但我确定我放错了地方。

这是 MyCountDownTimer 的片段 Class

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);

}
}

覆盖 activity 的 onStop 方法并使用类似

的代码
@Override
protected void onStop() {
    myCountDownTimer.cancel();
    super.onStop();
}

因此,只要您的 activity 进入后台,它就会取消与当前 activity 关联的任何计时器。