run()方法内的时间

时间:2013-06-06 07:13:30

标签: java android

我在run()方法中有一个简单的游戏循环。该课程正在实施Runnable。我只是想创建一些简单的计时代码来跟踪玩家玩的时间。假设我想在两分钟后结束比赛。

我不确定我这样做是因为我在屏幕上显示的时间不是秒,而是long时间格式,如1370502588.我做错了什么?

以下是run()方法内部代码的一部分:

// Game loop ---------------------------------------
@Override
public void run() {
// TODO Auto-generated method stub

// Time 
long startGameTime = 0;
long milliSeconds;
int seconds;

while (gameRunning) {
  if (!surfaceHolder.getSurface().isValid())
    continue;

  try {
    milliSeconds = System.currentTimeMillis() - startGameTime;
    seconds = (int) (milliSeconds / 1000);
    if (seconds > 120)
      // Game over
      canvas = surfaceHolder.lockCanvas();
      ...

编辑:LogCat

06-06 07:27:06.831: E/Trace(864): error opening trace file: No such file or directory (2)
06-06 07:27:07.601: D/libEGL(864): loaded /system/lib/egl/libEGL_emulation.so
06-06 07:27:07.611: D/(864): HostConnection::get() New Host Connection established 0x2a142400, tid 864
06-06 07:27:07.721: D/libEGL(864): loaded /system/lib/egl/libGLESv1_CM_emulation.so
06-06 07:27:07.721: D/libEGL(864): loaded /system/lib/egl/libGLESv2_emulation.so
06-06 07:27:07.731: D/dalvikvm(864): GC_CONCURRENT freed 232K, 10% free 7430K/8199K, paused 99ms+117ms, total 354ms
06-06 07:27:07.801: W/EGL_emulation(864): eglSurfaceAttrib not implemented
06-06 07:27:07.821: D/OpenGLRenderer(864): Enabling debug mode 0
06-06 07:27:08.121: I/Choreographer(864): Skipped 35 frames!  The application may be doing too much work on its main thread.
06-06 07:27:08.201: W/dalvikvm(864): threadid=12: thread exiting with uncaught exception (group=0x40a13300)
06-06 07:27:08.211: E/AndroidRuntime(864): FATAL EXCEPTION: Thread-88
06-06 07:27:08.211: E/AndroidRuntime(864): java.lang.IllegalArgumentException
06-06 07:27:08.211: E/AndroidRuntime(864):  at android.view.Surface.unlockCanvasAndPost(Native Method)
06-06 07:27:08.211: E/AndroidRuntime(864):  at android.view.SurfaceView$4.unlockCanvasAndPost(SurfaceView.java:785)
06-06 07:27:08.211: E/AndroidRuntime(864):  at se.test.game.GameLoop.run(GameLoop.java:269)
06-06 07:27:08.211: E/AndroidRuntime(864):  at java.lang.Thread.run(Thread.java:856)

2 个答案:

答案 0 :(得分:4)

而不是

long startGameTime = 0;

DO

long startGameTime = System.currentTimeMillis();

然后,你已经拥有的这条线更有意义:

milliSeconds = System.currentTimeMillis() - startGameTime;

在您的版本中,您将减去当前时间的0,这意味着用户自1970年1月1日起一直在播放。在我的版本中,您从当前时间中减去实际开始时间,结果是这两个时刻之间的时间跨度。

答案 1 :(得分:0)

startGameTime sis始终为0,因为它在本地运行()并且从未更新过。