我有一个基本的游戏循环,如下所示。但是当我滑出键盘时,循环运行得更快。我不明白这一点,因为我的延迟时间没有改变。之前 - 之后始终为 1 或 2 毫秒。谁能解释为什么会发生这种情况。 -谢谢
public abstract class GameLayout extends LinearLayout {
// App context
private Context context;
// Timer period
private long mPeriod =75;
// ---------[ GAME LOOP ]-----------------
protected Handler gameHandler;// = new Handler();
private Runnable gameRunnable = new Runnable() {
public void run() {
long before = SystemClock.uptimeMillis();
gameLoop();
postInvalidate(); // causes UI to be redrawn
long after = SystemClock.uptimeMillis();
long delay = mPeriod-(after-before);
if (gameHandler != null) {
if(delay >0)
gameHandler.postDelayed(this, delay);
else gameHandler.postDelayed(this, 0);
}
}
};
protected void startUpdateTimer() {
// System.out.println("start timer");
gameHandler = new Handler();
gameHandler.post(gameRunnable);
}
enter code here
protected void stopUpdateTimer() {
// System.out.println("stop timer");
gameHandler.removeCallbacks(gameRunnable);
gameHandler = null;
}
public void setUpdatePeriod(long updateDelay) {
mPeriod = updateDelay;
}
// -----------------------------------------------------
public GameLayout(Context c) {
super(c);
context = c;
}
public GameLayout(Context c, AttributeSet attrs) {
super(c, attrs);
context = c;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
try {
// Init game
initialize();
/**
* start update task. Which will fire onDraw in the future
*/
startUpdateTimer();
} catch (Exception e) {
// bug
e.printStackTrace();
}
最佳答案
onLayout
发生得非常频繁,并且肯定会通过轮换启动一两次。您没有停止 gameHandler
/gameRunnable
的旧实例,导致 gameRunnable
在每个布局上启动一次。如果没有实际看到您的 gameLoop
源,就不可能知道,但可能存在共享状态,导致您同时运行的 gameLoop
的多个实例导致问题 - 确保您只在一次运行一个 gameHandler
(在执行 gameLoop 之前尝试记录有关 Handler 的一些独特信息,看看情况是否如此)。
关于java - 键盘滑出/配置更改后 Android 循环速度更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5121201/