Android Render and Physics on separate threads?

I recently had a problem with my physics stopping racing in front of my rendering (they were in the same thread). After a few months, I solved the problem after about 20 minutes, creating a new topic and placing it in physics.

I find that having them completely separated from each other gives me much more control, and now my sprites move sequentially across all screens at all frame rates.

My question is, is it "better" to put logic and rendering in one thread or separate threads? The latter seems better to me, but does it cause any problems? (e.g. does battery life affect?)

thanks

+4
source share
3 answers

Yes, of course, it is better to use several threads, especially if the calculation is non-trivial, in which case you can experience the terrible "Do not respond to actions" dialog.

Something I would definitely consider would be AsyncTasks http://developer.android.com/reference/android/os/AsyncTask.html . Essentially, you would do all the physics calculations in the doInBackground method (which works in the background thread) and then periodically call publishProgress from the inside (which will execute the onProgressUpdate callback, where you will do all your rendering in the user interface thread).

0
source

In fact, the use of different threads to execute logic and visualize the user interface is indeed and always appreciated. And this is also true.

But processing / managing multiple threads requires a more complex responsibility for the programmer.

And since streams also increase battery consumption, we should therefore always use the stream very carefully.

Thus, the end result is the use of threads, but carefully. because the stream is useful, it is used optimally, but dangerously it is not used carefully.

0
source

You said ... "I use surfaceView, which, as I understand it, uses a separate stream for rendering (separately from the user interface stream) - so I have 3 threads"

It looks like you are assuming that by expanding SurfaceView, you are automatically provided with another main thread for the surface, which is separate from the user interface thread. I believe that this is not so.

From an Android developer link for SurfaceView: "One of the goals of this class is to provide a surface on which a secondary stream can be displayed on the screen." The keyword may be. You still have to create a separate stream yourself, SurfaceView just makes it easy to draw on canvas in a separate stream.

If you take LunarLander as an example, it has only two threads: the user interface thread and the manually created “LunarThread”, in which the physics is updated, and the canvas is drawn (via SurfaceHolder.lockCanvas ()) as quickly as possible, regardless of user interface thread.

0
source

All Articles