簡體   English   中英

為什么我的CountDownTimer沒有在onBackPressed()中停止?

[英]Why did my CountDownTimer not stop in onBackPressed()?

我的倒數計時器工作正常,但是當我在該時間的運行狀態下使用后退鍵時,我的倒數計時器沒有停止。 我已經嘗試了以下所有方法,但是它們都無法停止倒數計時器在后台運行。 搜索論壇並將其結果應用於我的項目后,我無法弄清楚代碼中的錯誤。 請任何人幫助我,我將非常感激。

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

}

我想你一定要用這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM