2
\$\begingroup\$

How do I calculate the time between frames on Android? I'm using this for the thread:

public class GameThread extends Thread
{
  private int FPS = 30;
  private double averageFPS;
  private SurfaceHolder surfaceHolder;
  private Game gamePanel;
  public boolean running;
  public static Canvas canvas;
  public static double deltaTime;

  public GameThread(SurfaceHolder surfaceHolder, Game gamePanel) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.gamePanel = gamePanel;
  }

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

    while(running) {
      startTime = System.nanoTime();
      canvas = null;

      //try locking the canvas for pixel editing
      try {
        canvas = this.surfaceHolder.lockCanvas();
        synchronized (surfaceHolder) {
          this.gamePanel.tick();
          this.gamePanel.render(canvas);
        }
      } catch (Exception e) {
      } finally {
        if(canvas!=null)
        {
          try {
            surfaceHolder.unlockCanvasAndPost(canvas);
          } catch(Exception e){
            e.printStackTrace();
          }
        }
      }

      timeMillis = (System.nanoTime() - startTime) / 1000000;
      waitTime = targetTime-timeMillis;

      try{
        sleep(waitTime);
      } catch (Exception e) {
      }

      deltaTime = waitTime;
      totalTime += System.nanoTime() - startTime;
      frameCount++;
      if(frameCount == FPS)
      {
        averageFPS = 1000/((totalTime/frameCount)/1000000);
        frameCount =0;
        totalTime = 0;
        System.out.println(averageFPS);
      }
    }
  }

  public void setRunning(boolean b)
  {
    running=b;
  }
}

I tried doing it like in normal Java, but it didn't work (it only lead to a crash).

\$\endgroup\$
4
  • \$\begingroup\$ "but it didn't work (it only lead to a crash)" is not helpful at all for us to help you. Where does it crash? At what line? What's the error message? \$\endgroup\$
    – Vaillancourt
    Nov 14, 2015 at 13:26
  • \$\begingroup\$ It lead to a chrash in a array list. It was a nullpointer exception \$\endgroup\$
    – user69046
    Nov 14, 2015 at 16:03
  • 1
    \$\begingroup\$ It's still unclear what you're asking. You do not specify what line causes the crash. Most of your code is within try-catch blocks so the exception would not pop out from the core of your code... \$\endgroup\$
    – Vaillancourt
    Nov 14, 2015 at 16:08
  • \$\begingroup\$ I used a completly different system which i speed translated to android. What i want is a way to calculate delta time on anroid \$\endgroup\$
    – user69046
    Nov 14, 2015 at 19:14

0