[英]Is it necessary to use a separate thread when using SurfaceView?
In Android, I am using a SurfaceView. 在Android中,我正在使用SurfaceView。 It is inside a FrameLayout, to draw a couple of things on a transparent layer over the top of a general XML layout (with standard textViews, buttons etc.) The drawing does not involve very intensive computation, and does not animate, it only updates in response to button presses.
它位于FrameLayout内部,用于在常规XML布局上方的透明层(带有标准的textView,按钮等)上绘制一些内容。该绘制不涉及非常密集的计算,并且不进行动画处理,仅更新响应按钮按下。
All the examples I have seen of SurfaceView use a separate thread for drawing, and then close down that thread in OnSurfaceDestroyed. 我在SurfaceView上看到的所有示例均使用单独的线程进行绘制,然后在OnSurfaceDestroyed中关闭该线程。
My code works without using a separate thread, but it does crash/freeze occasionally, especially when switching between orientations/applications. 我的代码无需使用单独的线程即可工作,但偶尔会崩溃/冻结,尤其是在方向/应用程序之间切换时。
So my question is, do I need to use an extra thread to prevent these crashes. 所以我的问题是,我是否需要使用额外的线程来防止这些崩溃。 And if not, is there any other specific thing I should do in OnSurfaceDestroyed?
如果没有,在OnSurfaceDestroyed中我还应该执行其他任何特定操作吗? (I'd rather not post all my code here, just looking for a simple yes/no response and reasons in a couple of sentences).
(我不想在这里发布我的所有代码,只是在几句话中寻找简单的是/否响应和原因)。
You don't need to have a separate thread, but it's often a good idea. 你并不需要有一个单独的线程,但它往往是一个好主意。
For example, take a look at Grafika's " multi-surface test " Activity. 例如,看一下Grafika的 “ 多表面测试 ”活动。 It has three overlapping SurfaceViews that are rendered from the UI thread.
它具有从UI线程渲染的三个重叠的SurfaceView。 If you click on the "bounce" button, it starts a new thread to control the animation, because it's simpler to do that way (it can sit in a loop and draw, instead of having to post timed draw events to the UI looper).
如果单击“弹跳”按钮,它将启动一个新线程来控制动画,因为这样做更简单(它可以循环播放并绘制,而不必将定时绘制事件发布到UI循环器) 。 The bounce thread stops when the Activity is paused.
当“活动”暂停时,退回线程停止。 Note the code doesn't do anything in
surfaceDestroyed()
. 请注意,代码在
surfaceDestroyed()
中不执行任何surfaceDestroyed()
。
The interaction between SurfaceView and the Activity lifecycle can be tricky. SurfaceView和Activity生命周期之间的交互可能很棘手。 A discussion can be found here .
可以在这里找到讨论。
(It can be tricky to get everything right.) ( 将所有事情正确处理可能很棘手 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.