ahmed nader ahmed nader - 5 months ago 18
Android Question

java multithreading in android

how to solve the problem in the log cat .. the error says wait time is negative and it crashes on imulator and external device

this is my code in java android activity

public void run() {
long startTime;
long timeMills;
long waitTime;
long totalTime = 0;
int frameCount = 0;
long targetTime = 1000/FPS;

while (running){
startTime = System.nanoTime();
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder){
this.gamePanel.update();
this.gamePanel.draw(canvas);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(canvas != null){
try {
surfaceHolder.unlockCanvasAndPost(canvas);
}catch (Exception e){
e.printStackTrace();
}
}
}
timeMills = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - timeMills;
try {
this.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
totalTime += System.nanoTime() - startTime;
frameCount++;
if(frameCount == FPS){
avrageFPS = 1000 / (totalTime/frameCount) / 1000;
frameCount = 0;
totalTime = 0;
System.out.print(avrageFPS);
}
}
}


and this is the log

java.lang.IllegalArgumentException: millis < 0: -136

Answer

Your code does this:

long targetTime = 1000/FPS;

while (...) {
    startTime = System.nanoTime();
    ... do lots of work ...
    timeMills = (System.nanoTime() - startTime) / 1000000;
    waitTime = targetTime - timeMills;

If the time required to prepare and render a frame exceeds targetTime, then waitTime will be negative. The complexity of your animation, and the value for FPS, affect how likely this is to happen.

The easiest fix is simply:

if (waitTime < 0) { waitTime = 0; }

That way, if your rendering is taking too long and you're missing deadlines, you don't sleep at all.

A better fix would be to structure the game to run off the display's timing, rather than having a fixed notion of frame rate, and to drop frames when you fall behind. More information about this can be found in this appendix to the graphics architecture doc.

Comments