[安卓]移动活动,但计时器仍在工作



我的应用程序遇到了问题,我做了一个使用CountDownTimer的游戏。单击后退按钮时,计时器给我带来了一些问题。

单击它时,应用程序将返回到"主菜单活动",但计时器会继续运行。完成后,"ScoreSend = new Intent(getApplicationContext(), PostScoreActivity.class);"正在工作,它正在窃听我的所有应用程序。

我尝试使用 onDestroy 等等,但它也没有很好地工作,我也听说过onBackPress,但我没有找到任何关于它的信息。

有人知道如何解决它吗?谢谢!:)

private void incrementAndCheckCounter() {
    if (TimeDone) {
        Intent ScoreSend;
        ScoreSend = new Intent(getApplicationContext(), PostScoreActivity.class);
        String ScoreString = String.valueOf(Score);
        ScoreSend.putExtra("FinalScore", ScoreString);
        ScoreSend.putExtra("WhatRank", "Hardcore");

        SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
        int high_score_hardcore = settings.getInt("highscore_hardcore_pref", 0);
        if (Score > high_score_hardcore) {
            ScoreSend.putExtra("HardcoreBig", true);
            SharedPreferences.Editor editor = settings.edit();
            editor.putInt("highscore_hardcore_pref", Score);
            editor.apply();
        }
        startActivity(ScoreSend);
        finish();
    } else {
        timer.cancel();
        timer = new CountDownTimer(MaxTime[LOST], 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Time.setText((millisUntilFinished / 1000) + " Seconds");

            }
            @Override
            public void onFinish() {
                TimeDone = true;
                Time.setText("GAME OVER!");
                incrementAndCheckCounter();
            }
        };
        timer.start();
    }
}

Activity onDestroyonStop中调用timer.cancel();,这将停止计时器,当按下后退按钮或在当前活动中调用finish方法

时调用,例如:
@Override
 protected void onStop() {
  super.onStop();
  if(timer!=null){
    // cancel timer here
     timer.cancel();
   }
}

并且可能incrementAndCheckCounter(); onFinish中的方法调用会导致问题。

在再次调用它之前,使用标志检查当前活动是否正在运行:

public boolean isActivityRunning=false;
@Override
 protected void onStart() {
    isActivityRunning=true;
   }

并在 onStop 中将其设为假:

@Override
     protected void onStop() {
        isActivityRunning=false;
       }

现在检查 Activity 是否在计时器的方法中运行onFinish然后再调用incrementAndCheckCounter方法,例如:

     @Override
        public void onFinish() {
            TimeDone = true;
            Time.setText("GAME OVER!");
            if(incrementAndCheckCounter)
              incrementAndCheckCounter();
        }

最新更新