2
所以我在網上找到了一個例子,我用他們爲我創建的蛇遊戲創建的處理程序。但是,當我從主頁面轉到遊戲視圖時,我再次點擊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);
}
}
這是我在我的遊戲活動的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();
}