我的应用程序出了问题,我做了一个使用CountDownTimer的游戏。 单击后退按钮时,计时器对我有些问题。
点击后,应用会返回主菜单活动'但计时器继续前进。 完成后," ScoreSend = new Intent(getApplicationContext(),PostScoreActivity.class);"正在工作,它正在窃听我的所有应用。
我曾尝试使用onDestroy等,但它也不起作用, 我也听说过onBackPressed但我还没有找到任何关于它的信息。
任何人都知道如何修复它? 谢谢! :)
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();
}
}
答案 0 :(得分:0)
在timer.cancel();
或onDestroy
onStop
中拨打Activity
,当按下后退按钮或在当前活动中调用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中将其设为false:
@Override
protected void onStop() {
isActivityRunning=false;
}
现在在调用onFinish
方法之前检查Activity是否在Timer的incrementAndCheckCounter
方法中运行,如:
@Override
public void onFinish() {
TimeDone = true;
Time.setText("GAME OVER!");
if(incrementAndCheckCounter)
incrementAndCheckCounter();
}