处理程序如何工作?为什么我的动画速度在我重新启动 activity 后翻倍?

How does handler work? Why does my animation's speed double after i restart activity?

所以我在网上找到了一个示例,并使用了他们为我创建的贪吃蛇游戏创建的处理程序。但是,当我从主页转到游戏视图然后单击 android 平板电脑并再次启动游戏视图时,我的动画速度似乎翻了一番。 这是处理程序。

class RefreshHandler extends Handler { //Makes animation possible
        @Override
        public void handleMessage(Message msg) {
            Snake.this.update();
            Snake.gamePanel.invalidate();
        }

    public void sleep(long delayMillis) {
        this.removeMessages(0);
        sendMessageDelayed(obtainMessage(0), delayMillis);
    }
}

这是我在创建游戏时调用的更新函数 activity;

private void update() {
    //contains some code borrowed from snake example
    long currentTime = System.currentTimeMillis();
    if (currentTime - lastUpdateTime >= delay) {
        if (!gamePaused) {
            gamePanel.invalidate();
            lastUpdateTime = currentTime;
        }
    }
    refreshHandler.sleep(delay);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //remove the title
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    //fullscreen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //Set top and left boundaries; ball tends to get stuck on these
    //set up the application context for toast notifications
    context = getApplicationContext();
    gamePanel = new GameView(this);
    drawColor.setColor(Color.GREEN);
    up=true;
    setContentView(gamePanel);
    lastUpdateTime = System.currentTimeMillis();
    update();
}

您需要在 onPause 中删除所有处理程序消息并在 onResume 中启动。 https://developer.android.com/training/multiple-threads/communicate-ui.html