简体   繁体   English

当活动不是当前活动时,如何告诉MyCountDownTimer退出?

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

The project i'm working on is an quiz with a timer on each question. 我正在从事的项目是每个问题都有计时器的测验。 for 30 seconds. 30秒。 I noticed that if you finish the test before the timer runs out, the timer doesn't stop running. 我注意到,如果您在计时器用尽之前完成测试,则计时器不会停止运行。 So if you head on to another test, the notification that you haven't finished the test will popup and override the current activity. 因此,如果您要进行另一项测试,则会弹出尚未完成测试的通知,并覆盖当前活动。 I tried using the cancel() method, but i'm sure I misplaced it. 我尝试使用cancel()方法,但是我确定我放错了位置。

Here is a snippet of the MyCountDownTimer Class 这是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);

}

This is a snippet of the Activity that implements the method 这是实现该方法的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);

}
}

Override onStop method of your activity and use code like 覆盖活动的onStop方法,并使用如下代码

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

Hence whenever your activity goes in background it will cancel any timer associated with current activity. 因此,只要您的活动进入后台,它将取消与当前活动关联的任何计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM