[英]Is there an easy way to set up Android to only update screen when it needs to?
I am making a board game. 我正在制作棋盘游戏。 The board doesn't ever move, but pieces on top of it sometimes do depending on user interaction.
电路板永远不会移动,但它上面的碎片有时会取决于用户的互动。 There are also UI elements which may update periodically.
还有一些UI元素可能会定期更新。
Right now the way I set it up is by overwriting the onDraw()
method of a SurfaceView
subclass. 现在我设置的方式是覆盖
SurfaceView
子类的onDraw()
方法。 I have a drawing thread that constantly calls postInvalidate()
in a while loop: 我有一个绘图线程,在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();
}
}
}
This is not efficient and is taking a lot of CPU. 这样效率不高,需要占用大量CPU。 Is there a easy way to get android to only update when something changes?
是否有一种简单的方法让android只在更改时更新?
You have the right idea, but it needs a bit of refinement. 你有正确的想法,但它需要一些改进。
You definitely do not want to loop as fast as the CPU can handle it though. 你绝对不想像CPU那样快速地循环。 You should be sleeping your Thread in every loop for a little while.
你应该在每个循环中暂停你的线程一段时间。 You most certainly do not need to do everything in your loop every millisecond.
你肯定不需要每毫秒都在你的循环中做所有事情。
I found this guide to FPS control to be incredible helpful in designing a game loop. 我发现这个FPS控制指南在设计游戏循环时非常有帮助。
This Android-specific game loop guide also provides a lot of great sample code and an in-depth explanation. 这个特定于Android的游戏循环指南还提供了许多很棒的示例代码和深入的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.