@Override
public void run() {
super.run();
final float timePerFrame = 1000 / Options.MAX_FPS;
float timeDiff;
while(!isInterrupted() && isRunning) {
timeDiff = System.currentTimeMillis();
mController.refresh();
timeDiff = timePerFrame - (timeDiff - System.currentTimeMillis());
try {
Thread.sleep(Math.max(Math.round(timeDiff), 0));
} catch(InterruptedException e) {
// do nothing
e.printStackTrace();
}
}
Log.e("GameThread", "Thread dead.");
}
这就是我的线程基本上在做的事情。
Options.MAX_FPS = 30;
为了限制每秒的帧数,在每次刷新之间有某种睡眠时间。刷新方法如下所示:
公共同步无效刷新(){ int mRotation = Math.round((360 +((-1)*mAccelerometer [0] * 4.5f))%360);mObject.setRotation(mRotation);
// get canvas from surfaceview
if(mSurfaceHolder != null) {
// do all calculations.
if(Looper.myLooper() == Looper.getMainLooper()) {
log("on main thread!");
} else {
log("Not on main thread");
}
Canvas mCanvas = mSurfaceHolder.lockCanvas();
if (mCanvas != null) {
// shift x offset
mScreenWidth = mCanvas.getWidth();
mScreenHeight = mCanvas.getHeight();
// draw black background, clear everything.
mCanvas.drawRect(new Rect(0,0,mScreenWidth, mScreenHeight), mBlackPaint);
// shift & draw all viewobjects if still visible
for(ViewObject view: mViewObjectList.toArray(new ViewObject[mViewObjectList.size()])) {
view.shiftX(-1 * Options.Gameplay.Environment.MOVING_SPEED);
if(view.getX() + view.getWidth() < 0) {
mViewObjectList.remove(view);
}
if(view.getCurrentBitmap() != null)
mCanvas.drawBitmap(view.getCurrentBitmap(), new Rect(0,0,view.getCurrentBitmap().getWidth(), view.getCurrentBitmap().getHeight()), new Rect(view.getX(), view.getY(), view.getX()+ view.getWidth(), view.getY()+view.getHeight()), new Paint());
view.nextFrame();
}
// draw object
final Bitmap sBitmap = mObject.getCurrentBitmap();
mObject.nextFrame();
if(sBitmap != null) {
mCanvas.drawBitmap(sBitmap, new Rect(0, 0, sBitmap.getWidth(), sBitmap.getHeight()), new Rect(mObject.getX(), mObject.getY(), sBitmap.getWidth(), sBitmap.getHeight()), new Paint());
} else log("bitmap = null!");
}
mSurfaceHolder.unlockCanvasAndPost(mCanvas);
}
}
线程持续运行了一段时间,正在绘制背景元素(即使我的旋转还不能正常工作,但那是另一回事了..),背景“似乎”在移动(就像横向卷轴一样),但在某些情况下随机时间点,没有任何 ADB LogCat 消息(不仅限于应用程序,而是整个 LogCat 输出) - 线程简单地停止。不画了。没有什么。我没有调用中断或将 isRunning 设置为 false,因为“线程已死”。消息也没有写入 LogCat。我不知道发生了什么。谢谢你的帮助。