为什么我的CountDownTimer没有在onBackPressed()中停止?

时间:2018-10-31 09:44:36

标签: java android countdowntimer

我的倒数计时器工作正常,但是当我在时间的运行状态下使用后退键时,我的倒数计时器没有停止。我已经尝试了以下所有方法,但是它们都无法停止倒数计时器在后台运行。 搜索论坛并将其结果应用于我的项目后,我无法弄清楚代码中的错误。请任何人帮助我,我将非常感激。

 @Override
protected void onDestroy() {
    if (countDownTimer != null) {
        countDownTimer.cancel();

    }
    super.onDestroy();
   finish();

}


@Override
protected void onPause() {


    if (countDownTimer!=null) {
        countDownTimer.cancel();

    }
    super.onPause();
    finish();

}

@Override
protected void onStop() {


    if (countDownTimer!=null) {
        countDownTimer.cancel();

    }
    super.onStop();
    finish();

}

@Override
public void onBackPressed() {


    if (countDownTimer!=null) {
        countDownTimer.cancel();
    }
    super.onBackPressed();
    finish();

}

我完整的修改后的代码

public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;

List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;

private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        takeAction();

    }
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

    textViewCountDown = findViewById(R.id.text_view_countdown);
    relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
    linearLayout = (LinearLayout) findViewById(R.id.linearView);
    textColorDefaultCd = textViewCountDown.getTextColors();


    fetchQuestions();

    questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);

    questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
        @Override
        public void onChanged(@Nullable final List<Questions> words) {
            // Update the cached copy of the words in the adapter.
            mQuestions = words;
            //Collections.shuffle(mQuestions);
            Collections.addAll(mQuestions);

        }
    });

}



private void fetchQuestions() {


    DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();

    Service service = DataServiceGenerator.createService(Service.class);

    Call<List<QuestionsModel>> call = service.getQuestions();

    call.enqueue(new Callback<List<QuestionsModel>>() {
        @Override
        public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
            if (response.isSuccessful()){

                if (response != null){
                    List<QuestionsModel> questionsModelList = response.body();

                    for (int i = 0; i < questionsModelList.size(); i++){
                        String question = questionsModelList.get(i).getQuestion();
                        String answer = questionsModelList.get(i).getAnswer();
                        String opta = questionsModelList.get(i).getOpta();
                        String optb = questionsModelList.get(i).getOptb();
                        String optc = questionsModelList.get(i).getOptc();

                        Questions questions = new Questions(question, answer, opta, optb, optc);

                        questionsViewModel.insert(questions);
                    }

                    handler = new Handler();//add this
                    handler.postDelayed(runnable,1000);

          /*  Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            takeAction();

                        }
                    }, 3000);*/




                }

            }else{

            }
        }

        @Override
        public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {

        }
    });

}

private void setQuestionView()
{
    txtQuestions.setText(currentQ.getQuestion());
    rda.setText(currentQ.getOptA());
    rdb.setText(currentQ.getOptB());
    rdc.setText(currentQ.getOptC());
    qid++;


}

private void startCountDown() {
    countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            timeLeftInMillis = millisUntilFinished;
            updateCountDownText();
        }

        @Override
        public void onFinish() {
            timeLeftInMillis = 0;
            updateCountDownText();
            Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); //Your score
            intent.putExtras(b); //Put your score to your next Intent
            startActivity(intent);
            finish();
        }
    }.start();
}

private void updateCountDownText() {
    int minutes = (int) (timeLeftInMillis / 1000) / 60;
    int seconds = (int) (timeLeftInMillis / 1000) % 60;

    String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);

    textViewCountDown.setText(timeFormatted);

    if (timeLeftInMillis < 10000) {
        textViewCountDown.setTextColor(Color.RED);
    } else {
        textViewCountDown.setTextColor(textColorDefaultCd);
    }
}



private void takeAction() {
    relativeLayout.setVisibility(View.GONE);
    linearLayout.setVisibility(View.VISIBLE);

    textViewCountDown.setVisibility(View.VISIBLE);
    timeLeftInMillis = COUNTDOWN_IN_MILLIS;
    startCountDown();



    currentQ = mQuestions.get(qid);
    txtQuestions = (TextView)findViewById(R.id.textView1);
    rda=(RadioButton)findViewById(R.id.radio0);
    rdb=(RadioButton)findViewById(R.id.radio1);
    rdc=(RadioButton)findViewById(R.id.radio2);
    btnNext=(Button)findViewById(R.id.button1);
    setQuestionView();
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);

            if (grp.getCheckedRadioButtonId() == -1){
                Toast.makeText(getApplicationContext(),
                        "Please Select an Answer",
                        Toast.LENGTH_SHORT)
                        .show();
                return;

            }else{
               // countDownTimer.cancel();

            }

            RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());

            grp.clearCheck();
            //Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());

            if(currentQ.getAnswer().equals(answer.getText()))
            {
                score++;
                Log.d("score", "Your score"+score);
            }else{

            }
            if(qid<10){
                currentQ=mQuestions.get(qid);
                setQuestionView();
            }else{
                Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
                Bundle b = new Bundle();
                b.putInt("score", score); //Your score
                intent.putExtras(b); //Put your score to your next Intent
                startActivity(intent);
                finish();
            }
        }
    });
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(handler!=null){
        handler.removeCallbacks(runnable);
    }
    if (countDownTimer != null) {
        countDownTimer.cancel();
        countDownTimer = null;

    }
    finish();

}


@Override
protected void onPause() {
    super.onPause();
   if(handler!=null){
        handler.removeCallbacks(runnable);
    }

    if (countDownTimer!=null) {
        countDownTimer.cancel();
        countDownTimer = null;

    }
    finish();

}

@Override
protected void onStop() {
    super.onStop();
    if(handler!=null){
        handler.removeCallbacks(runnable);
    }
    if (countDownTimer!=null) {
        countDownTimer.cancel();
        countDownTimer = null;

    }
    finish();

}

@Override
public void onBackPressed() {
    if(handler!=null){
        handler.removeCallbacks(runnable);
    }
    if (countDownTimer!=null) {
        countDownTimer.cancel();
        countDownTimer = null;
    }
    finish();
}

}

1 个答案:

答案 0 :(得分:0)

我认为您必须使用此

@Override
public void onBackPressed() {


    if (countDownTimer!=null) {
        countDownTimer.cancel();
        countDownTimer = null;
    }
    finish();

}

更新

3秒钟后您使用处理程序,我不知道为什么

         Handler handler = new Handler();
         handler.postDelayed(new Runnable() {
             @Override
             public void run() {
                 takeAction();
                }
         }, 3000);

尝试像这样在全局中创建处理程序和可运行包

private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
             @Override
             public void run() {
                 takeAction();
                }
         }

然后在onResponse()中使用它

 handler = new Handler();//add this
 handler.postDelayed(runnable,3000);

最后进入您的onStop()onDestroy()

if(hacdler!=null){
    hacdler.removeCallbacks(runnable)
}