Search code examples
javaandroidpostdelayed

PostDelayed function going faster and faster


So I have a snake app were I'm trying to make it so that it waits for on screen touch before a new run.

And I figured best way would have the code stop updating the snake and continue the UI update. So i have a game state that is running and one that is lost.

And when I play the first game it is going as it should but when I die and go over it gets faster and faster.

I'm thinking that it is something with my way of calling the postDelay method in both Running and Lost. But if i only call it in Running and make lost just run the game again without any pause it runs smoothly.

private void startUpdateHandler(){
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            if (gameEngine.getCurrentGameState() == GameState.running){
                gameEngine.Update();
                handler.postDelayed(this, updateDelay);
            }

            if (gameEngine.getCurrentGameState() == GameState.lost){
                if (trial) {
                    onGameLost();
                    trial = false;
                }
                if (touch){
                    gameEngine.initgame();
                    gameEngine.setToRunning();
                    trial = true;
                }
                handler.postDelayed(this, updateDelay);
            }

            snakeView.setSnakeViewMap(gameEngine.getMap());
            snakeView.invalidate();
        }
    }, updateDelay);
}

I might not get the postDelayed method right, I've tried to search for a method to pause the code and wait for a click. But that has just broken the code for me. And I got the code working if I didn't have any delay between when you die and start over.

New to stackoverflow so if my question is bad I'll try fixing it!

***** EDIT ******

Solved this myself, i put handler.postDelayed(this, updateDelay); in the back of the run function. I saw that when i had 3000ms delay that everytime i died it jumped one extra time each time it moved, and when i had 3 handler.postDelayed(this, updateDelay); it jumped 2 times extra each time i moved.

So I concluded that if i write the postdelay more than 1 time it stacks up over time. Not sure why but it works perfectly now, I would appreciate anyone who could explain this!


Solution

  • I'm not sure how your internals function, but you may have methods changing the state, and since you have two nonnested if calls it may be calling the handler multiple times. I also feel like this will continually add onto the stack and will eventually result in an overflow error. You can resolve the first issue by using switches or if else.

    You may also want to consider using an interval like implementation, and then update the interval when necessary. Have a look at Android's Timer