处理程序如何工作?重启活动后,为什么我的动画速度加倍?

时间:2015-03-03 04:15:54

标签: android android-activity android-handler

所以我在网上找到了一个例子,我使用了他们为我创建的蛇游戏创建的处理程序。然而,当我从主页面进入游戏视图然后我再次点击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);
    }
}

这是我的更新功能,在我的游戏活动的创建期间调用;

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();
}

1 个答案:

答案 0 :(得分:0)

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