That Thatson
That Thatson

Reputation: 309

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. 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.

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

}

This is a snippet of the Activity that implements the method

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

}
}

Upvotes: 0

Views: 95

Answers (1)

Satty
Satty

Reputation: 1372

Override onStop method of your activity and use code like

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

Hence whenever your activity goes in background it will cancel any timer associated with current activity.

Upvotes: 1

Related Questions