【问题标题】:How does handler work? Why does my animation's speed double after i restart activity?处理程序如何工作?为什么我重新开始活动后我的动画速度会加倍?
【发布时间】:2015-05-03 15:26:27
【问题描述】:

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

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

这是我在游戏活动的 oncreate 期间调用的更新函数;

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

【问题讨论】:

    标签: android android-activity android-handler


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多