【发布时间】:2012-10-30 02:45:13
【问题描述】:
我正在制作棋盘游戏。板子永远不会移动,但它上面的部分有时会根据用户交互而移动。还有一些 UI 元素可能会定期更新。
现在我设置它的方式是覆盖SurfaceView 子类的onDraw() 方法。我有一个绘图线程,在 while 循环中不断调用postInvalidate():
class PanelThread extends Thread
{
//...
long sleepTime = 0;
long nextGameTick = System.currentTimeMillis();
@Override
public void run()
{
Canvas c;
while (_run)
{ // When setRunning(false) occurs, _run is
c = null; // set to false and loop ends, stopping thread
try
{
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder)
{
// Insert methods to modify positions of items in onDraw()
_panel.postInvalidate();
}
} finally
{
if (c != null)
{
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
nextGameTick += MILLISECONDS_PER_FRAME;
sleepTime = nextGameTick - System.currentTimeMillis();
if(sleepTime >= 0)
{
try
{
sleep(sleepTime, 0);
} catch (InterruptedException e)
{
continue;
}
}
else
{
//we're behind, oh well.
System.out.println("behind!");
nextGameTick = System.currentTimeMillis();
}
}
}
这效率不高,并且占用大量 CPU。有没有一种简单的方法可以让 android 仅在发生变化时才更新?
【问题讨论】:
-
您是否查看过 Android Pro Games 的游戏循环示例?
标签: android multithreading performance android-canvas cpu-usage