Android Loop Faster After KeyBoard Slides Out / Configs Changed
I have a basic game loop shown below. But when I slide the keyboard out, the loop runs way faster. I don't understand this because my delay time does not change. Before - After is constantly 1 or 2 milliseconds. Can anyone explain why this is happening. -Thanks
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);
game开发者_Go百科Handler = 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
happens pretty frequently, and certainly would be kicked off once or twice by a rotation. You're not stopping the old instance of the gameHandler
/gameRunnable
, leading to the gameRunnable
being kicked off once on each layout. Without actually seeing your gameLoop
source it's impossible to know, but there's probably shared state causing multiple instances of the gameLoop
you have running at once to cause problems - make sure you only are running one one gameHandler
at a time (try logging some unique information about the Handler before executing the gameLoop to see if that's the case).
精彩评论