我的班级MainActivity启动Activity" GameActivity"通过用户交互(按钮)。我的类GameView是我的类GameActivity的视图,并且具有Runnable接口的实现。在内部我已经实现了一个Handler作为计时器,它连续运行trigger()方法。当gameIsOver == true
游戏停止并启动GameOverActivity时。在GameOverActivity中,我添加了一个Button来提交分数。如果您按下按钮,您将返回MainView并开始新游戏。
现在问题:在我玩游戏之后GameOverActivity开始,我提交得分并开始一个新游戏或者我结束游戏并退出(而不是杀死)应用程序。 在这两种方式中,有时GameOverActivity再次启动并向我显示游戏结束。怎么会这样?从哪里打来的?我猜计时器或Runnable没有正确停止,但我真的不知道如何防止这个问题......
PS:如果GameOverActivity在游戏中开始,那么游戏并没有真正结束。如果我按下手机上的后退按钮,我就会回到游戏中。
GameView.java
private Handler timerHandler;
private boolean gameIsOver;
private long triggerTime, counter;
public void init() {
gameIsOver = false;
triggerTime = 1000;
counter = 0;
timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (gameIsOver) {
return;
}
long millis = System.currentTimeMillis() - startTime;
invalidate();
if (millis > (triggerTime * counter)) {
counter++;
GameView.this.trigger();
}
timerHandler.postDelayed(this, 250);
}
};
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 250);
}
触发器()方法中的:
if (gameIsOver) {
timerHandler.removeCallbacks(timerRunnable);
invalidate();
Intent intent = new Intent(this.context, GameOverActivity.class);
intent.putExtra("EXTRA_SCORE", score);
// some more extras...
((Activity) this.context).startActivity(intent);
((Activity) this.context).finish();
}
编辑:
GameActivity.java
public class GameActivity extends Activity {
private GameView game;
private int level;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game);
Intent intent = getIntent();
level = intent.getExtras().getInt("EXTRA_LEVEL");
game = (GameView) findViewById(R.id.game);
game.setLevel(level);
}
}