【问题标题】:Is there an easy way to set up Android to only update screen when it needs to?有没有一种简单的方法可以将 Android 设置为仅在需要时更新屏幕?
【发布时间】: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


【解决方案1】:

您的想法是正确的,但需要稍加改进。

您肯定希望以 CPU 可以处理的速度循环。 你应该在每个循环中让你的线程休眠一段时间。您当然不需要每毫秒都在循环中执行所有操作。

我发现这个guide to FPS control 对设计游戏循环非常有帮助。

这个Android-specific game loop guide还提供了很多很棒的示例代码和深入的解释。

【讨论】:

  • 啊当然完全忽略了实际控制FPS。将其归咎于草率。谢谢!
猜你喜欢
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
相关资源
最近更新 更多